2015-12-08 31 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