Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Number of arguments and point-free in Haskell [duplicate]

With multiple pattern-matching, different numbers of arguments are impossible, even with point-free!

foo True b = b + 2
foo _ = id

doesn't work for example. But

foo True = (+2)
foo _ = id

does. Sometimes we can use point-free only in one part of the function, so...

Why? Is it too hard for GHC? :'(

like image 582
L01man Avatar asked Jul 14 '12 20:07

L01man


People also ask

How do you write free points in Haskell?

Pointfree Style g . h than to write let fn x = f (g (h x)) . This style is particularly useful when deriving efficient programs by calculation and, in general, constitutes good discipline. It helps the writer (and reader) think about composing functions (high level), rather than shuffling data (low level).

What is twice in Haskell?

twice then returns a function which takes an argument and applies f to it twice: twice f = \x -> f (f x) .

How do you pass arguments in Haskell?

You have to pass file1 etc. to runQuery like every other function argument: main = do (file1:file2:file3:_) <- getArgs checkdata command <- getLine runQuery file1 file2 file3 (words command) runQuery file1 file2 file3 ("queryname":parameter1:parameter2) = do ...

What does NS mean in Haskell?

The sequence (n:ns) is a shorthand for head - tail. Quite literally, the first value, the head, is called n and the remained are the other, potentially plural, n s, which is why it is called ns . Haskell has pattern matching.


1 Answers

Why? Is it too hard for GHC?

No. It is not at all too hard for GHC. Actually, this is the fault of the Haskell Report.

See: Haskell Report 2010 > Declarations and Bindings > Function bindings

A function binding binds a variable to a function value. The general form of a function binding for variable x is:

x p11 … p1k match1

x pn1 … pnk matchn

[...blah blah...]

Translation: The general binding form for functions is semantically equivalent to the equation (i.e. simple pattern binding):

x = \ x1 … xk -> case (x1, …, xk) of

(p11, …, p1k) match1

(pn1, …, pnk) matchn
where the xi are new identifiers.

(emphasis mine)

While function definitions are semantically equivalent to a lambda & case expression, they are not necessarily compiled that way, as Mihai suggests.

The thing is, the Haskell report defines function declarations such that they must have the same number of inputs on the left-hand side of the equation. This is made clear by the fact that k remains the same on both the 1st and the nth function declaration lines (and by implication, all lines in-between). This is the reason for the restriction; it has nothing to do with GHC's implementation details.

tl;dr

The choice not to allow it is just a matter of style. – augustss

like image 90
Dan Burton Avatar answered Sep 30 '22 06:09

Dan Burton