[英]Exercise with functor, applicative and monads in Haskell
I'm doing exercises from the book "Programming in Haskell (2nd Edition)" and I have some problems in understanding the following:我正在做《Haskell 编程(第 2 版)》一书中的练习,但在理解以下内容时遇到了一些问题:
"Given the following type of expressions "给定以下类型的表达式
data Expr a = Var a | Val Int | Add (Expr a) (Expr a)
deriving Show
that contain variables of some type a
, show how to make this type into instances of the Functor , Applicative and Monad classes.包含某种类型a
变量,展示如何使这种类型成为Functor 、 Applicative和Monad类的实例。 With the aid of an example, explain what the >>=
operator for this type does."借助示例,解释此类型的>>=
运算符的作用。”
I found a solution to the first question, which is the same as here: https://github.com/evturn/programming-in-haskell/blob/master/12-monads-and-more/12.05-exercises.hs (ex. 7), that is type correct.我找到了第一个问题的解决方案,与这里相同: https : //github.com/evturn/programming-in-haskell/blob/master/12-monads-and-more/12.05-exercises.hs (例 7),即类型正确。
The problem is that I cannot find out the sense of this exercise and the meaning of what this solution actually does.问题是我无法找出这个练习的意义以及这个解决方案实际做什么的意义。
To understand the solution, you need to get an intuition over a Functor
, an Applicative
and a Monad
.要理解解决方案,您需要对Functor
、 Applicative
和Monad
有一个直觉。
That being said fmap
, <*>
and >>=
is just a way for one to be able to transform a data within an arbitrary F
in your case that's an Expr
from a -> b
话虽fmap
, <*>
和>>=
只是一种能够在任意F
中转换数据的方法,在您的情况下,它是来自a -> b
的Expr
Take a look at the Type class definitions of Functor
, Applicative
and Monad
for example.例如,看看Functor
、 Applicative
和Monad
的 Type 类定义。
class Functor f where
fmap :: (a -> b) -> f a -> f b
class Functor f => Applicative f where
<*> :: f (a -> b) -> f a -> f b
class Applicative m => Monad m where
>>= :: m a -> (a -> m b) -> m b
Though on the bigger picture, these functions also execute effects of the algebraic datatype that have the type class instances for it.尽管从更大的角度来看,这些函数还执行具有类型类实例的代数数据类型的效果。
For example, I will provide the rough definition of the Maybe
monad.例如,我将提供Maybe
monad 的粗略定义。
instance Monad Maybe where
(Just something) >>= f = f something
Nothing >>= _ = Nothing
In this context, the bind or >>=
combinator returns Nothing
if there is Nothing
for the input else it applies the arbitrary f
on something
such that f
is a transformation from a -> Maybe b
which satisfies the definition of the >>=
combinator which is ma -> (a -> mb) -> mb
where m
is the Maybe
datatype.在此背景下,绑定或>>=
组合子返回Nothing
如果Nothing
为输入其他适用的任意f
上something
,使得f
是从改造a -> Maybe b
这满足的定义>>=
组合子即ma -> (a -> mb) -> mb
其中m
是Maybe
数据类型。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.