2016-04-06 98 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