2015-12-08 28 views
-2

我已经实现序列的实施方式中 '::单子米=> [毫安] - 下面Haskell中测试不同MAPM

sequence' [] = return [] 
sequence' (m : ms) 
    = m >>= 
     \ a -> 
     do as <- sequence' ms 
      return (a : as) 

我需要测试以下的 MAPM实现> M [A]' ::单子米=>(A - > mb)个 - >并[a] - >米并[b]

mapM'a f as = sequence' (map f as) 

mapM'b f [] = return [] 
mapM'b f (a : as) 
    = f a >>= \b -> mapM'b f as >>= \ bs -> return (b : bs) 

mapM'f f [] = return [] 
mapM'f f (a : as) = 
    do b <- f a 
     bs <- mapM'f f as 
     return (b : bs) 

mapM'g f [] = return [] 
mapM'g f (a : as) 
    = f a >>= 
     \ b -> 
     do bs <- mapM'g f as 
      return (b : bs) 

mapM'h f [] = return [] 
mapM'h f (a : as) 
    = f a >>= 
     \ b -> 
     do bs <- mapM'h f as 
     return (bs ++ [b]) 

请让我知道如何测试和验证的MAPM上述实现 - 我应该调用哪个函数。一些示例将非常有用。

感谢

+2

看起来你的老师正试图让你习惯'do'符号转化为'>> ='的应用。尝试通过各种'mapM'函数运行像'\ x - > Just(x + 1)'这样的简单函数和像[[1,2,3]]这样的测试列表并查看输出。 (提示:其中一个实现不正确!) –

回答

1

一类的单子的你可能会发现在你的测试有用的是free monads在各种仿函数。免费的monads往往对你在实现中可能犯的任何错误特别敏感。您可以使用任何合理灵活的基函数,例如[]进行测试。

data Free f a = Pure a 
       | Free (f (Free f a)) 

instance Functor f => Functor (Free f) where 
    fmap f (Pure a) = Pure (f a) 
    fmap f (Free xs) = Free (fmap (fmap f) xs) 

instance Functor f => Applicative (Free f) where 
    pure = Pure 
    (<*>) = ap 

instance Functor f => Monad (Free f) where 
    Pure x >>= f = f x 
    Free xs >>= f = Free (fmap (>>= f) xs) 

instance (Eq (f (Free f a)), Eq a) => Eq (Free f a) where 
    Pure a == Pure b = a == b 
    Free fa == Free fb = fa == fb 
    _ == _ = False