问题描述
Haskell新手在这里,试图编写代码来解析数学表达式。代码:
isDigit :: Char - > Bool
isDigit c = c> ='0'&& c< ='9'
parseNumber :: String - > Maybe(String,String)
parseNumber [] = Just(,)
parseNumber(h:ls)
| isDigit h
| p == Nothing = Just([h],ls) - 找到数字<<<错误!!
|否则=正好(h:fst d,snd d) - 以数字
|结尾h =='。'
| p == Nothing = Nothing - 以点
|结束not('。'`elem`(snd d))= Just(h:(fst d),snd d) - 我们不需要多个点
|否则=无 - 不是数字,停止查找!
其中
p = parseNumber ls
只需d = parseNumber ls - 浮点版本p。如果p是Nothing,则不使用
这个函数应该采用一个以数字开头的字符串,并且返回与表达式其余部分分离的数字。例子:
我认为这个嵌套的守卫的语法读起来非常好,但它不起作用。
对于标记的行,错误读取:
Haskell中不允许链式警卫吗?或者我以某种方式错误地写这篇文章?另外,还有什么替代方法可以以简单的方式将逻辑链接起来?
不,但您可以使用案例, d像:
parseNumber :: String - > Maybe(String,String)
parseNumber [] = Just(,)
parseNumber(h:ls)
| isDigit h =
case()的
()| p == Nothing = Just([h],ls)
|否则=正好(h:fst d,snd d) - 以数字
|结尾h =='。'=
case()
()| p == Nothing = Nothing
| not('。'`elem`(snd d))= Just(h:(fst d),snd d)
|否则=无
其中
p = parseNumber ls
只是d = parseNumber ls
另外,如果以多种方式运作,如果以相似的方式运作( if True | p1 - > b; | p2 - > c
)。 b
Haskell newbie here, trying to write code to parse math expressions.Code:
isDigit :: Char -> Bool
isDigit c = c >= '0' && c <= '9'
parseNumber :: String -> Maybe (String, String)
parseNumber [] = Just ("", "")
parseNumber (h:ls)
| isDigit h
| p == Nothing = Just([h], ls) -- Digit found <<< ERROR!!
| otherwise = Just (h:fst d, snd d) -- Ends in a digit
| h == '.'
| p == Nothing = Nothing -- Ends in a point
| not ('.' `elem` (snd d)) = Just (h:(fst d), snd d) -- We don't want multiple dots
| otherwise = Nothing -- Not a number, stop looking!
where
p = parseNumber ls
Just d = parseNumber ls -- Float version of p. Not used if p is Nothing
This function is supposed to take a string that starts with a number, and returns the number separated from the rest of the expression. Example:
I think this nested guards' syntax reads really nicely, but it doesn't work.The error reads, for the marked line:
Are chained guards not allowed in Haskell? Or am I writting this wrongly somehow? Also, what alternatives do I have to chain logic in a simple way?
No, but you can use cases if you'd like:
parseNumber :: String -> Maybe (String, String)
parseNumber [] = Just ("", "")
parseNumber (h:ls)
| isDigit h =
case () of
() | p == Nothing = Just([h], ls)
| otherwise = Just (h:fst d, snd d) -- Ends in a digit
| h == '.' =
case () of
() | p == Nothing = Nothing
| not ('.' `elem` (snd d)) = Just (h:(fst d), snd d)
| otherwise = Nothing
where
p = parseNumber ls
Just d = parseNumber ls
Alternatively, multiway if works in a similar manner (if True | p1 -> b ; | p2 -> c
).
这篇关于是否有可能在Haskell中嵌套卫兵?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!