簡體   English   中英

Haskell String to Maybe List

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM