我正在学习monad,这是我的第一个工作(除了琐碎的monad).随意批评其中的一切无情.我对"更惯用"和"更优雅"的回应特别感兴趣.
该monad计算执行的绑定数.
data C a = C {value :: a, count :: Int} deriving (Show)
instance Monad C where
(>>=) (C x c) f = C (value $ f x) (c + 1)
return x = C x 0
add :: (Num a) => a -> a -> C a
add x y = return $ x + y
-- Simpler way to do this? foldM is obviously something different.
mysum [x] = return x
mysum (x:xs) = mysum xs …Run Code Online (Sandbox Code Playgroud)