简体   繁体   English

如何正确使用Maybe base?

[英]How to use Maybe base correctly?

I write a code to convert a string to be a list of Intger: 我编写了将字符串转换为Intger列表的代码:

convert::String -> Maybe [Int]
convert (c:cs) 
    isDigit c            = Just(c: (convert cs):[])
    otherwise            = Nothing

and it shows an error... 它显示一个错误...

test.hs:15:26: error:
parse error on input ‘=’
Perhaps you need a 'let' in a 'do' block?
e.g. 'let x = 5' instead of 'x = 5'

Why is that so... 为什么会这样...

While there are other compile errors in your code, the reason you're getting the error message about the parse error is because you are not including the pipe character used in guards. 虽然您的代码中还有其他编译错误,但收到有关parse错误的错误消息的原因是因为您不包括在防护中使用的管道字符。

convert (c:cs) 
    | isDigit c            = Just(c: (convert cs):[])
    | otherwise            = Nothing

There were several errors in your code. 您的代码中有几个错误。 You need to try to convert each character, which gives a Maybe Int . 您需要尝试转换每个字符,从而得到Maybe Int Then you loop on the string using mapM inside the Maybe monad : 然后,在Maybe monad中使用mapM循环处理字符串:

import Data.Char

convertChar :: Char -> Maybe Int
convertChar c = if isDigit c then Just $ ord c else Nothing

convert :: String -> Maybe [Int]
convert = mapM convertChar

Another way of looking at V. Semeria's answer is to use sequence (from the Traversable type class) with map : 看着另一种方式V. Semeria的答案是使用sequence (从Traversable类型类) map

import Data.Char -- for ord

convertChar :: Char -> Maybe Int
convertChar c = if isDigit c then Just $ ord c - 48 else Nothing

convert :: String -> Maybe [Int]
-- Start with String -> [Maybe Int], then convert
-- the [Maybe Int] to Maybe [Int]
convert = sequence . map convertChar

This is a common pattern, so Traversable also provides traverse , which in this case is equivalent to sequence . map 这是一种常见的模式,因此Traversable也提供了traverse ,在这种情况下, traverse相当于sequence . map sequence . map . sequence . map

convert :: Traversable t => t Char -> Maybe (t Int)
convert = traverse converChar

Some examples (most of the instances of Traversable available by default aren't very interesting, but various tree types can have instances). 一些示例(默认情况下可用的Traversable大多数实例不是很有趣,但是各种树类型可以具有实例)。

> convert "123"
Just [1,2,3]
> convert (Just '1')
Just (Just 1)
> convert (True, '2')
Just (True, 2)
> convert (Right '1')
Just (Right 1)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM