[英]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
I want to get Just [L,L,R,R]. 我想得到Just [L,L,R,R]。 But looks like i failed :( Here is the error message!
但看起来我失败了:(这是错误信息!
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)’
Change this 改变这个
'L' -> Just (L : readSquareTransition xs)
'R' -> Just (R : readSquareTransition xs)
to this 对此
'L' -> fmap (L :) $ readSquareTransition xs
'R' -> fmap (R :) $ readSquareTransition xs
The problem is that readSquareTransition returns a Maybe [SquareTurn]
, so you can't apply (:)
to it ( (:)
requires a List). 问题是readSquareTransition返回一个
Maybe [SquareTurn]
,因此你不能对它应用(:)
( (:)
需要一个List)。 fmap
however lets you apply into the Just
(while preserving a Nothing
). 然而,
fmap
允许你应用到Just
(同时保留Nothing
)。
A modular way of doing this would be to define readSquareTurn
first which defines how to turn a Char
into a single SquareTurn
(with the possibility of failure): 这样做的模块化方法是首先定义
readSquareTurn
,定义如何将Char
转换为单个SquareTurn
(可能失败):
readSquareTurn :: Char -> Maybe SquareTurn
readSquareTurn x = case x of
'L' -> Just L
'R' -> Just R
_ -> Nothing
and then use mapM :: (a -> Maybe b) -> [a] -> Maybe [b]
to process the whole String
like so: 然后使用
mapM :: (a -> Maybe b) -> [a] -> Maybe [b]
来处理整个String
如下所示:
readSquareTransition :: String -> Maybe [SquareTurn]
readSquareTransition = mapM readSquareTurn
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.