简体   繁体   English

在 Haskell 中使用函子、应用程序和 monad 进行练习

[英]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变量,展示如何使这种类型成为FunctorApplicativeMonad类的实例。 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 .要理解解决方案,您需要对FunctorApplicativeMonad有一个直觉。

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 -> bExpr

Take a look at the Type class definitions of Functor , Applicative and Monad for example.例如,看看FunctorApplicativeMonad的 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为输入其他适用的任意fsomething ,使得f是从改造a -> Maybe b这满足的定义>>=组合子即ma -> (a -> mb) -> mb其中mMaybe数据类型。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM