I’m doing lists concatenation in the following ways (an example, using GHC):
myConcat :: [[a]] -> [a]
myConcat xs = foldr (++) [] xs
myConcat = foldr (++) []
Can someone explain to me please why and how the above definitions work and this one does not:
myConcat xs = foldr (++) []
Is the last line of code intentionally not allowed (for a reason like the constructs might become confusing, it is useless, etc) or is it something deeper, maybe related to currying…
I hope I can shed some light on this, it really puzzles me :/
LATER EDIT: Besides the explanations given below, I’ve found a good source of information on the matter to be the section “Partial function application and currying” from Chap. 4 “Functional Programming” from the book “Real World Haskell”. The book is available freely online.
Lets review the different versions:
This is the usual way, providing an argument, which is consumed by
foldr. The type is[[a]] -> [a], because we have an argument of type[[a]]on the left side, which yields[a]when fed to the right side.Here
foldris partially applied, so we return a function which can take an additional argument, a list of lists. So what we get back from the right side is already what we need, it is not a “syntactical suger”, but another way to express the same thing as the first version. The type is again[[a]] -> [a]: We have nothing on the left side, but give back a function of that signature at the right side.Here
foldris partially applied as well, and we return a function that can take an argument as before, but our definition has an additional argumentxs, which isn’t used on the right side. The compiler doesn’t “know” that it is this argument we want to have applied to the right side. The type ist -> [[a]] -> [a]. Why?Assume you have a square function:
What you are doing is essentially the same as providing an addition, unused argument:
The function still “works”, e.g.
sqr 3 "bla"yields 9, but the type signature is off, and the unused argument is… erm, unused. The unused argument has no fixed type, as it can be virtually “anything”, it doesn’t matter. So it gets type variable (t) in the signature.