2016-04-06 81 views
3
readSquareTransition :: String -> Maybe [SquareTurn] 
readSquareTransition [] = Just [] 
readSquareTransition (x:xs) = case x of 
     'L' -> Just (L : readSquareTransition xs) 
     'R' -> Just (R : readSquareTransition xs) 
     _  -> Nothing 

我想要得到只是[L,L,R,R]。不过貌似我没:(以下是错误信息!Haskell String to Maybe List

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)’ 

回答

3

这样做的一个模块化的方式是定义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 
3

更改此

'L' -> Just (L : readSquareTransition xs) 
'R' -> Just (R : readSquareTransition xs) 

这个

'L' -> fmap (L :) $ readSquareTransition xs 
'R' -> fmap (R :) $ readSquareTransition xs 

的问题是,readSquareTransition返回Maybe [SquareTurn],这样你就可以不适用(:)(:)需要一个列表)。fmap但是可以让你申请到Just (同时保留Nothing)。

+0

你不得不放弃'Just':'readSquareTransition'已经返回一个Maybe的东西。 – gallais

+0

糟糕,我正在粗心大意,你是对的,我会改变这个...... – jamshidh

+1

你应该在'readSquareTransition xs'或$''前面加括号,或者使用中缀'(<$>)'代替'fmap'。 – gallais