functional programming - Haskell function definition syntax -
i'm doing lists concatenation in following ways (an example, using ghc):
myconcat :: [[a]] -> [a] myconcat xs = foldr (++) [] xs myconcat = foldr (++) []
can explain me please why , how above definitions work , 1 not:
myconcat xs = foldr (++) []
is last line of code intentionally not allowed (for reason constructs might become confusing, useless, etc) or deeper, maybe related currying...
i hope can shed light on this, puzzles me :/
later edit: besides explanations given below, i've found source of information on matter section "partial function application , currying" chap. 4 "functional programming" book "real world haskell". book available freely online.
lets review different versions:
myconcat xs = foldr (++) [] xs
this usual way, providing argument, consumed foldr
. type [[a]] -> [a]
, because have argument of type [[a]]
on left side, yields [a]
when fed right side.
myconcat = foldr (++) []
here foldr
partially applied, return function can take additional argument, list of lists. right side need, not "syntactical suger", way express same thing first version. type again [[a]] -> [a]
: have nothing on left side, give function of signature @ right side.
myconcat xs = foldr (++) []
here foldr
partially applied well, , return function can take argument before, our definition has additional argument xs
, isn't used on right side. compiler doesn't "know" this argument want have applied right side. type t -> [[a]] -> [a]
. why?
assume have square function:
sqr :: int -> int sqr x = x*x
what doing same providing addition, unused argument:
sqr:: int -> t -> int sqr x y = x*x
the function still "works", e.g. sqr 3 "bla"
yields 9, type signature off, , unused argument is... erm, unused. unused argument has no fixed type, can virtually "anything", doesn't matter. gets type variable (t
) in signature.
Comments
Post a Comment