Mylies
Mylies

Reputation: 436

Dont understand whats on in this haskell code

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?

Upvotes: 2

Views: 151

Answers (1)

Thomas M. DuBuisson
Thomas M. DuBuisson

Reputation: 64740

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.

Upvotes: 2

Related Questions