[英]Haskell String to Maybe List
readSquareTransition :: String -> Maybe [SquareTurn]
readSquareTransition [] = Just []
readSquareTransition (x:xs) = case x of
'L' -> Just (L : readSquareTransition xs)
'R' -> Just (R : readSquareTransition xs)
_ -> Nothing
我想得到Just [L,L,R,R]。 但看起来我失败了:(这是错误信息!
src/StudentSources/LangtonsAnt.hs:231:24:
Couldn't match expected type ‘[SquareTurn]’
with actual type ‘Maybe [SquareTurn]’
In the second argument of ‘(:)’, namely ‘readSquareTransition xs’
In the first argument of ‘Just’, namely
‘(L : readSquareTransition xs)’
src/StudentSources/LangtonsAnt.hs:232:24:
Couldn't match expected type ‘[SquareTurn]’
with actual type ‘Maybe [SquareTurn]’
In the second argument of ‘(:)’, namely ‘readSquareTransition xs’
In the first argument of ‘Just’, namely
‘(R : readSquareTransition xs)’
改变这个
'L' -> Just (L : readSquareTransition xs)
'R' -> Just (R : readSquareTransition xs)
对此
'L' -> fmap (L :) $ readSquareTransition xs
'R' -> fmap (R :) $ readSquareTransition xs
问题是readSquareTransition返回一个Maybe [SquareTurn]
,因此你不能对它应用(:)
( (:)
需要一个List)。 然而, fmap
允许你应用到Just
(同时保留Nothing
)。
这样做的模块化方法是首先定义readSquareTurn
,定义如何将Char
转换为单个SquareTurn
(可能失败):
readSquareTurn :: Char -> Maybe SquareTurn
readSquareTurn x = case x of
'L' -> Just L
'R' -> Just R
_ -> Nothing
然后使用mapM :: (a -> Maybe b) -> [a] -> Maybe [b]
来处理整个String
如下所示:
readSquareTransition :: String -> Maybe [SquareTurn]
readSquareTransition = mapM readSquareTurn
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.