我对Haskell很新,我想解决一些问题。 我正在尝试创建一个小程序,它将从text.txt文件中读取表达式并返回结果。
首先,我阅读了文本并将我读到的内容转换为字符串:
module Main where
import Data.Char
convert :: String -> String
convert = unlines . (map convertLine) . lines
convertLine :: String -> String
convertLine = unwords . (map convertWord) . words
convertWord :: String -> String
convertWord s = (toUpper (head s)):(tail s)
main = do
name <- readFile "test.txt"
putStr $ convert name
现在,我想解析该字符串,我从:
开始parse :: (Read a, Num a, Fractional a) => String -> [SyntacticalElement a]
parse "" = []
parse putStr = element : (parse rest)
where (element, rest) = next_elem putStr
我在这里得到错误:next_elem不在范围内 知道为什么吗?
更新
module Main where
import Data.Char
convert :: String -> String
convert = unlines . (map convertLine) . lines
convertLine :: String -> String
convertLine = unwords . (map convertWord) . words
convertWord :: String -> String
convertWord s = (toUpper (head s)):(tail s)
main = do
name <- readFile "test.txt"
putStr $ convert name
number = ['0'..'9'] ++ ['.']
operator = ['+', '-', '*', '/']
open_brackets = ['(', '[']
close_brackets = [')', ']']
brackets = open_brackets ++ close_brackets
allowed_chars = number ++ operator ++ brackets
parse :: (Read a, Num a, Fractional a) => String -> [SyntacticalElement a]
parse "" = []
parse putStr = element : (parse rest)
where (element, rest) = next_elem putStr
next_elem :: (Read a, Num a, Fractional a) => String -> (SyntacticalElement a, String)
next_elem s@(first:_)
| is_open_bracket first = (to_sublist content, rest_b)
| is_operator first = (to_operator operator, rest_o)
| is_number first = (to_number number, rest_n)
| is_close_bracket first = error "Unexpected closing bracket!"
| otherwise = error $ "Invalid Expression: \"" ++ s ++ "\""
where (number, rest_n) = span is_number s
(operator, rest_o) = span is_operator s
(content, rest_b) = parse_bracket s
答案 0 :(得分:1)
因为编译器不知道next_elem
的含义。为什么会这样?在哪里定义?
对于这些情况,使用interact
通常很方便,而不是费心去读取文件。