如何将列表列入可能的列表

时间:2016-04-13 04:19:34

标签: haskell monads

readtree :: Char -> Char -> Maybe Tree
readtree x y = case x of
    'L' -> case y of
        '1' -> Just L1
        '2' -> Just L2
        _   -> Nothing
    'R' -> case y of
        '1' -> Just R1
        '2' -> Just R2
        _   -> Nothing
    'T' -> Just Top
    'D' -> Just Down
    _   -> Nothing
treelist :: String -> Maybe [Tree]
treelist = mapM readtree

如果我输入" L1TDR2",我想将它改为Just [L1,Top,Down,R2]列表。但它看起来很失败。

Couldn't match type ‘Char -> Maybe Tree’ with ‘Maybe Tree’
Expected type: Char -> Maybe Tree
  Actual type: Char -> Char -> Maybe Tree
Probable cause: ‘readtree’ is applied to too few arguments
In the first argument of ‘mapM’, namely ‘readtree’
In the expression: mapM readtree

2 个答案:

答案 0 :(得分:2)

也许像

x $: xs = (x:) <$> xs

readTrees ('L':'1':rest) = L1  $: readTrees rest
readTrees ('T':rest)     = Top $: readTrees rest
readTrees []             = Just []
readTrees _              = Nothing

答案 1 :(得分:0)

也许像

import Control.Monad.Trans.State

readTrees = evalStateT $ many readTree <* (gets null >>= guard) where
  readTree = StateT uncons >>= \case
    'L' -> StateT uncons >>= \case
      '1' -> return L1
      '2' -> return L2
      _   -> empty
    'R' -> StateT uncons >>= \case
      '1' -> return L1
      '2' -> return L2
      _   -> empty
    'T' -> return Top
    'D' -> return Down
    _   -> empty