我正在處理函子,應用程序和單子。在自定義數據類型上定義和使用monadic結構?
這些例子只是爲了說明的基礎知識:
data User a = Age a deriving (Show, Eq, Ord)
函子(施加非上下文功能到單一上下文數據類型):
instance Functor User where
fmap f (Age a) = Age (f a)
functorFunction :: Int -> Int
functorFunction e = e + 1
main = do
print $ fmap functorFunction (Age 22)
應用型(施加簡單的功能,以多個上下文數據類型):
instance Applicative User where
pure a = Age a
(<*>) (Age a) = fmap a
applicativeFunction :: Int -> Int -> Int
applicativeFunction e1 e2 = e1 + e2
main = do
print $ pure (applicativeFunction) <*> (Age 44) <*> (Age 65)
我經歷learnyouahaskell而一直沒能找到
1)如何定義我的「用戶」型單子結構簡單的解釋,和2)什麼功能的單子提供與,例如,一個應用功能?
您的用戶類型同構於[Identity]函子(https://hackage.haskell.org/package/base-4.9.0.0/docs/Data-Functor-Identity.html#t:Identity )。看看[其源代碼](https://hackage.haskell.org/package/base-4.9.0.0/docs/src/Data.Functor.Identity.html#line-97) –
關於2,請參見[這個](http://stackoverflow.com/a/38719766/3072788)。 – Alec
或[this](http://stackoverflow.com/questions/17409260/what-advantage-does-monad-give-us-over-an-applicative)。 – arrowd