Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Problem understanding treesort in Haskell

I am trying to figure out how exactly does treesort from here work (I understand flatten, insert and foldr).

I suppose what's being done in treesort is applying insert for each element on the list thus generating a tree and then flattening it. The only problem I can't overcome here is where the list (that is the argument of the function) is hiding (because it is not written anywhere as an argument except for the function type declaration).

One more thing: since dot operator is function composition, why is it an error when I change: treesort = flatten . foldr insert Leaf to treesort = flatten( foldr insert Leaf )?

like image 680
Jerry Avatar asked Mar 23 '26 04:03

Jerry


1 Answers

what's being done in treesort is applying insert for each element on the list thus generating a tree and then flattening it.

Exactly right.

[Where is the list hiding?]

In a functional language, you don't have to give the arguments of a value of function type. For example if I write

f = concat . map (map toUpper) 

I get a function of type [[Char]] -> [Char]. This function expects an argument even though there's no argument in the defining equation. It's exactly the same as if I had written

f strings = (concat . map (map toUpper)) strings

Since the dot operator is function composition, why is it wrong to change f . g to f (g)?

They don't mean the same thing. What happens when each is applied to x?

(f . g) x  = f (g x)

(f (g)) x  = (f g) x

You can see the applications associate differently, and f. g is different from f g.

It's a type error because foldr insert Leaf is a function from lists to trees, and flatten is meant to be applied to a single tree, not to a function.

like image 108
Norman Ramsey Avatar answered Mar 24 '26 19:03

Norman Ramsey



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!