Dont understand whats on in this haskell code

為{幸葍}努か 提交于 2020-01-04 04:34:07

问题


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

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) 

But this returns a int, when the add function requires a bag be returned. Can anyone explain to me how this works?


回答1:


Terms and Discussion

type Bag a = 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

A function from any type to the constant number zero.

countB :: Eq a => Bag a -> a -> Int
countB b e = b e

In short, this is just function application. Apply the function named b to the input e.

Rewriting for fun and learning

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



来源:https://stackoverflow.com/questions/54995025/dont-understand-whats-on-in-this-haskell-code

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!