3 ms·
Looks like you're being downvoted, but I have to agree with you, especially given some of the examples right at the top. foldr (:) [] [1,2,3] There is abso
by jsmeaton 12y ago
Looks like you're being downvoted, but I have to agree with you, especially given some of the examples right at the top.
foldr (:) [] [1,2,3]
There is absolutely nothing natural about that line of code unless you happen to already have some background. I executed that in the sandbox and got:
[1,2,3]:: Num a => [a]
And I still don't know what was achieved.
- daffodil2 12y agoFor a function f and a value x, foldr f x [a,b,c] gets turned into f(a, f(b, f(c, x))) '(:)' is list concatenation, so the result is 1 : (2 : (3 : [])) (Here we are writing list concatenation in infix notation, rather than the customary prefix notation). '[1,2,3]' is shorthand for 1 : (2 : (3: [])) in Haskell.
- jsmeaton 12y agoThanks, I appreciate the walk through. So it's essentially just copying an array (in this particular example). I'd still argue that the syntax is not natural - since you have to have specific knowledge of the operator and the function.
- tel 12y agoSyntactic naturality seems like it's mostly a function of familiarity. That said, the example has, for a lot of mathematical reasons, a great deal of semantic naturality. It's far from immediately obvious, but `foldr (:) []` is the way to copy singly-linked lists. In particular, if you look at a linked list as a degenerate tree then what `foldr f z` does is replace all of the nodes with `f` and the single leaf with `z`. Since cons, i.e. (:), creates a node and nil, i.e. [], is that single leaf then `foldr (:) []` is a very natural way to do nothing at all. So it's kind of the most boring interesting example imaginable.