问题描述
我有一些haskell代码,我正在试图按自己的方式工作,但我不了解其中发生了什么.
I have some haskell code Im trying to work my way thourgh but I dont have understand what is going in it.
type Bag a = a -> Int
emptyB :: Bag a
emptyB = \e -> 0
countB :: Eq a => Bag a -> a -> Int
countB b e = b e
我知道Bag类型是一个接受通用对象并返回Int的函数,而countB基本上是Bag的包装,该包装获取该Bag中通用对象的数量.但是我真的不明白那件事.我如何修改袋子里的东西?还是包本身?从我看来,添加到书包中将是
I understand that the Bag type is a function that takes in a generic object and returns a Int and countB is basically a wrapper for Bag that gets the number of generic objects in that Bag. But I dont really understand anything past that. How do I modify whats in the bag? Or the bag itself? From what I figure adding to the bag would be something like
addB :: Eq a => Bag a -> a -> Bag a
addB bag num = bag (num+bag)
但是,当add函数要求返回bag时,这将返回一个int值.谁能向我解释这是如何工作的?
But this returns a int, when the add function requires a bag be returned. Can anyone explain to me how this works?
推荐答案
术语和讨论
type Bag a = a -> Int
此处 Bag
不是对象.它只是一种类型- a->的别名.Int
.如果您有一个 a
类型的值,它将计算并返回一个 Int
类型的值.就是这样.没有袋子,没有可以添加东西的结构.最好不要把它叫做袋子.
Here Bag
is not an object. It is just a type - an alias for a -> Int
. If you have a value of type a
it will compute and return a value of type Int
. That's it. There is no Bag, no structure to which you can add things. It would be better to not even call this a Bag.
emptyB :: Bag a
emptyB = \e -> 0
从任何类型到常数0的函数.
A function from any type to the constant number zero.
countB :: Eq a => Bag a -> a -> Int
countB b e = b e
简而言之,这只是函数应用程序.将名为 b
的函数应用于输入的 e
.
In short, this is just function application. Apply the function named b
to the input e
.
为了娱乐和学习而重写
我很欣赏您可以使用函数来模仿结构-这是常见的编程语言类分配.您可以将一个 Bag a
和另一个 Bag a
然后合并在一起,例如通过添加两个单独袋子的计数来返回新的 countB
-很酷.
I appreciate that you can use functions to imitate structures - it's a common programming language class assignment. You can take a Bag a
and another Bag a
then union them, such as returning a new countB
by adding the counts of the two individual bags - cool.
...但这似乎太多了.在继续进行作业之前(我想是吗?),您可能应该对基础知识有所了解.
... but this seems too much. Before moving on with your assignment (did I guess that right?) you should probably become slightly more comfortable with the basics.
如果重写不带类型别名的函数,可能会更容易:
It might be easier if you rewrite the functions without the type alias:
emptyB :: a -> Int
emptyB = \e -> 0
-- or: emptyB e = 0
-- or: emptyB _ = 0
-- or: emptyB = const 0
袋子或没有袋子,这只是一个功能.
Bag or no bag, it's just a function.
countB :: Eq a => (a -> Int) -> a -> Int
countB b e = b e
采用 a
并生成 Int
的函数可以被赋予一个值(变量 e
的类型为 a
),并生成一个 Int
.
A function that takes an a
and produces an Int
can... be given a value (the variable e
is of type a
) and produce an Int
.
这篇关于不了解此haskell代码中的内容的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!