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

最佳答案

一种模块化的方式是首先定义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

10-01 13:19