TLDR: Is there a Haskell library that offers function definitions (preferably with concise notation or naming) for handling common patterns of multi-argument function composition such as those in APL?
Full Question:
I'm new to Haskell and I have recently found myself asking the types of composition questions that other new Haskell users have asked such as how to compose a unary function with a binary function or how to compose two binary functions in a specific way. The point-free solutions to both of these are fairly unintuitive (either (.)(.)(.) or LiftM2 (.)) despite the goal of the function composition pattern being fairly clear (and probably quite common).
I have spent a little time with the APL language and really loved how simple and powerful the function composition model is. For example, here is a diagram of many composition patterns that can be accomplished in extremely terse notation that is actually fairly readable after one spends some time in the language.
Any of these APL patterns could be accomplished in Haskell by writing a simple lambda expression. For example, I have the following line in one of my Haskell files
(...) = (.)(.)(.)
which alternatively (and probably more clearly) could have been written
(...) = \f g x y = f (g x y)
or with a clearer name as
_1_atop_2 = \f g x y = f (g x y)
so that I can easily compose a unary function with a binary function in point-free style in the main portions of my code. For example, to define a distance function between real values, I just compose absolute value with subtraction:
dist = abs ... (-)
or
dist = _1_atop_2 abs (-)
(In this case, the more explicit style of dist x y = abs $ x - y is arguably clearer, but in more elaborate cases the point free is nicer.)
My question is this: Is there any Haskell library that offers definitions of these composition patterns? I can obviously just create my own module with the trivial lambda definitions for these patterns, but I am wondering if there is some standard notation/naming convention for doing this.
As far as I know, there isn't a single Haskell library that provides them all. While some are built-in, you'd have to collect the rest from various libraries. Here's table 19 (Combinators in Haskell) from Conor Hoekstra's Combinatory Logic and Combinators in Array
Languages:
Name
Library
I
id
Prelude
K
const
Prelude
W
join
Control.Monad
C
flip
Prelude
B
(.)
Prelude
S
(<*>) / ap
Control.Applicative
B₁
(.:)
Data.Composition
Ψ
on
Data.Function
Φ
liftA2
Control.Applicative
A
($)
Prelude
I'm learning haskell, and I have a lot of difficulty with mentally parsing many haskell expressions I come across.
Of course, I expect that, with enough practice, mentally parsing haskell will become second-nature, but in the meantime, in order to make sense of what I come across, I'd like to find some automatic way to translate an arbitrary "standard haskell"1 expression into one in which all "ambiguous"2 sub-expressions have been eliminated by introducing the necessary parentheses.
For example, it would translate the expression
f g h i
...into
((f g) h) i
..., or
a -> b -> c -> d
...into
a -> (b -> (c -> d))
..., etc.
Preferably, this would be a tool I can access with my phone, since I do much of my reading on haskell away from a proper computer.
1Of course, no such tool could possibly work with custom operators of unknown fixity and associativity. By "standard haskell" I mean the stuff defined in the prelude and in the standard haskell library.
2I'm using "ambiguous" here as shorthand for "ambiguous in the absence of precedence rules". E.g. 2 + 3 * 5 is ambiguous unless there's some precedence rule that settles the question of which of the two operations will be performed first.
If you really want to go to the work of it, you could write a TemplateHaskell function to do this for you - you essentially just walk the AST and add parens at will. I started doing that, but realized it will get pretty long and tedious pretty fast. I think it may be more convenient for the moment for you to only think about currying when it actually comes into play (with functions that are not fully applied).
However, there is a trick you can use for a subcase of your problem: parens around operators whose fixity and associativity you aren't familiar with. In GHCi, after booting up with the right flags, just wrap the expression you are interested in inspecting in $([| <expression> |]). Then, you get to see a parenthesized version of your expression before the result of evaluating it.
$ ghci -ddump-splices -XTemplateHaskell
Prelude> $([| 1 + 2 ^ 3 * 4 |])
<interactive>:1:3-21: Splicing expression
[| 1 + 2 ^ 3 * 4 |] ======> (1 + ((2 ^ 3) * 4))
33
Prelude> $([| 1 <$ pure 4 >>= \x -> const mempty =<< [(+),(*)] <*> [1,2] <* [False] |])
<interactive>:2:3-77: Splicing expression
[| 1 <$ pure 4
>>=
(\ x_a6PT -> const mempty =<< [(+), (*)] <*> [1, 2] <* [False] |]
======>
((1 <$ (pure 4))
>>=
(\ x_a6PT
-> ((const mempty) =<< (([(+),(*)] <*> [1,2]) <* [False]))))
[]
Prelude>
However, this definitely won't fix the type signatures or function applications the way you want.
It's not exactly what you're asking for, but I've found using HLint to warn me about unnecessary parens when I'm writing Haskell to be a big help when I'm reading.
You may also find the chart on page 23 of Bernie Pope's "A tour of the Haskell Prelude" helpful. I've included a copy below.
Say I have a general recursive definition in haskell like this:
foo a0 a1 ... = base_case
foo b0 b1 ...
| cond1 = recursive_case_1
| cond2 = recursive_case_2
...
Can it always rewritten using foldr? Can it be proved?
If we interpret your question literally, we can write const value foldr to achieve any value, as #DanielWagner pointed out in a comment.
A more interesting question is whether we can instead forbid general recursion from Haskell, and "recurse" only through the eliminators/catamorphisms associated to each user-defined data type, which are the natural generalization of foldr to inductively defined data types. This is, essentially, (higher-order) primitive recursion.
When this restriction is performed, we can only compose terminating functions (the eliminators) together. This means that we can no longer define non terminating functions.
As a first example, we lose the trivial recursion
f x = f x
-- or even
a = a
since, as said, the language becomes total.
More interestingly, the general fixed point operator is lost.
fix :: (a -> a) -> a
fix f = f (fix f)
A more intriguing question is: what about the total functions we can express in Haskell? We do lose all the non-total functions, but do we lose any of the total ones?
Computability theory states that, since the language becomes total (no more non termination), we lose expressiveness even on the total fragment.
The proof is a standard diagonalization argument. Fix any enumeration of programs in the total fragment so that we can speak of "the i-th program".
Then, let eval i x be the result of running the i-th program on the natural x as input (for simplicity, assume this is well typed, and that the result is a natural). Note that, since the language is total, then a result must exist. Moreover, eval can be implemented in the unrestricted Haskell language, since we can write an interpreter of Haskell in Haskell (left as an exercise :-P), and that would work as fine for the fragment. Then, we simply take
f n = succ $ eval n n
The above is a total function (a composition of total functions) which can be expressed in Haskell, but not in the fragment. Indeed, otherwise there would be a program to compute it, say the i-th program. In such case we would have
eval i x = f x
for all x. But then,
eval i i = f i = succ $ eval i i
which is impossible -- contradiction. QED.
In type theory, it is indeed the case that you can elaborate all definitions by dependent pattern-matching into ones only using eliminators (a more strongly-typed version of folds, the generalisation of lists' foldr).
See e.g. Eliminating Dependent Pattern Matching (pdf)
I don't think I quite understand currying, since I'm unable to see any massive benefit it could provide. Perhaps someone could enlighten me with an example demonstrating why it is so useful. Does it truly have benefits and applications, or is it just an over-appreciated concept?
(There is a slight difference between currying and partial application, although they're closely related; since they're often mixed together, I'll deal with both terms.)
The place where I realized the benefits first was when I saw sliced operators:
incElems = map (+1)
--non-curried equivalent: incElems = (\elems -> map (\i -> (+) 1 i) elems)
IMO, this is totally easy to read. Now, if the type of (+) was (Int,Int) -> Int *, which is the uncurried version, it would (counter-intuitively) result in an error -- but curryied, it works as expected, and has type [Int] -> [Int].
You mentioned C# lambdas in a comment. In C#, you could have written incElems like so, given a function plus:
var incElems = xs => xs.Select(x => plus(1,x))
If you're used to point-free style, you'll see that the x here is redundant. Logically, that code could be reduced to
var incElems = xs => xs.Select(curry(plus)(1))
which is awful due to the lack of automatic partial application with C# lambdas. And that's the crucial point to decide where currying is actually useful: mostly when it happens implicitly. For me, map (+1) is the easiest to read, then comes .Select(x => plus(1,x)), and the version with curry should probably be avoided, if there is no really good reason.
Now, if readable, the benefits sum up to shorter, more readable and less cluttered code -- unless there is some abuse of point-free style done is with it (I do love (.).(.), but it is... special)
Also, lambda calculus would get impossible without using curried functions, since it has only one-valued (but therefor higher-order) functions.
* Of course it actually in Num, but it's more readable like this for the moment.
Update: how currying actually works.
Look at the type of plus in C#:
int plus(int a, int b) {..}
You have to give it a tuple of values -- not in C# terms, but mathematically spoken; you can't just leave out the second value. In haskell terms, that's
plus :: (Int,Int) -> Int,
which could be used like
incElem = map (\x -> plus (1, x)) -- equal to .Select (x => plus (1, x))
That's way too much characters to type. Suppose you'd want to do this more often in the future. Here's a little helper:
curry f = \x -> (\y -> f (x,y))
plus' = curry plus
which gives
incElem = map (plus' 1)
Let's apply this to a concrete value.
incElem [1]
= (map (plus' 1)) [1]
= [plus' 1 1]
= [(curry plus) 1 1]
= [(\x -> (\y -> plus (x,y))) 1 1]
= [plus (1,1)]
= [2]
Here you can see curry at work. It turns a standard haskell style function application (plus' 1 1) into a call to a "tupled" function -- or, viewed at a higher level, transforms the "tupled" into the "untupled" version.
Fortunately, most of the time, you don't have to worry about this, as there is automatic partial application.
It's not the best thing since sliced bread, but if you're using lambdas anyway, it's easier to use higher-order functions without using lambda syntax. Compare:
map (max 4) [0,6,9,3] --[4,6,9,4]
map (\i -> max 4 i) [0,6,9,3] --[4,6,9,4]
These kinds of constructs come up often enough when you're using functional programming, that it's a nice shortcut to have and lets you think about the problem from a slightly higher level--you're mapping against the "max 4" function, not some random function that happens to be defined as (\i -> max 4 i). It lets you start to think in higher levels of indirection more easily:
let numOr4 = map $ max 4
let numOr4' = (\xs -> map (\i -> max 4 i) xs)
numOr4 [0,6,9,3] --ends up being [4,6,9,4] either way;
--which do you think is easier to understand?
That said, it's not a panacea; sometimes your function's parameters will be the wrong order for what you're trying to do with currying, so you'll have to resort to a lambda anyway. However, once you get used to this style, you start to learn how to design your functions to work well with it, and once those neurons starts to connect inside your brain, previously complicated constructs can start to seem obvious in comparison.
One benefit of currying is that it allows partial application of functions without the need of any special syntax/operator. A simple example:
mapLength = map length
mapLength ["ab", "cde", "f"]
>>> [2, 3, 1]
mapLength ["x", "yz", "www"]
>>> [1, 2, 3]
map :: (a -> b) -> [a] -> [b]
length :: [a] -> Int
mapLength :: [[a]] -> [Int]
The map function can be considered to have type (a -> b) -> ([a] -> [b]) because of currying, so when length is applied as its first argument, it yields the function mapLength of type [[a]] -> [Int].
Currying has the convenience features mentioned in other answers, but it also often serves to simplify reasoning about the language or to implement some code much easier than it could be otherwise. For example, currying means that any function at all has a type that's compatible with a ->b. If you write some code whose type involves a -> b, that code can be made work with any function at all, no matter how many arguments it takes.
The best known example of this is the Applicative class:
class Functor f => Applicative f where
pure :: a -> f a
(<*>) :: f (a -> b) -> f a -> f b
And an example use:
-- All possible products of numbers taken from [1..5] and [1..10]
example = pure (*) <*> [1..5] <*> [1..10]
In this context, pure and <*> adapt any function of type a -> b to work with lists of type [a]. Because of partial application, this means you can also adapt functions of type a -> b -> c to work with [a] and [b], or a -> b -> c -> d with [a], [b] and [c], and so on.
The reason this works is because a -> b -> c is the same thing as a -> (b -> c):
(+) :: Num a => a -> a -> a
pure (+) :: (Applicative f, Num a) => f (a -> a -> a)
[1..5], [1..10] :: Num a => [a]
pure (+) <*> [1..5] :: Num a => [a -> a]
pure (+) <*> [1..5] <*> [1..10] :: Num a => [a]
Another, different use of currying is that Haskell allows you to partially apply type constructors. E.g., if you have this type:
data Foo a b = Foo a b
...it actually makes sense to write Foo a in many contexts, for example:
instance Functor (Foo a) where
fmap f (Foo a b) = Foo a (f b)
I.e., Foo is a two-parameter type constructor with kind * -> * -> *; Foo a, the partial application of Foo to just one type, is a type constructor with kind * -> *. Functor is a type class that can only be instantiated for type constrcutors of kind * -> *. Since Foo a is of this kind, you can make a Functor instance for it.
The "no-currying" form of partial application works like this:
We have a function f : (A ✕ B) → C
We'd like to apply it partially to some a : A
To do this, we build a closure out of a and f (we don't evaluate f at all, for the time being)
Then some time later, we receive the second argument b : B
Now that we have both the A and B argument, we can evaluate f in its original form...
So we recall a from the closure, and evaluate f(a,b).
A bit complicated, isn't it?
When f is curried in the first place, it's rather simpler:
We have a function f : A → B → C
We'd like to apply it partially to some a : A – which we can just do: f a
Then some time later, we receive the second argument b : B
We apply the already evaluated f a to b.
So far so nice, but more important than being simple, this also gives us extra possibilities for implementing our function: we may be able to do some calculations as soon as the a argument is received, and these calculations won't need to be done later, even if the function is evaluated with multiple different b arguments!
To give an example, consider this audio filter, an infinite impulse response filter. It works like this: for each audio sample, you feed an "accumulator function" (f) with some state parameter (in this case, a simple number, 0 at the beginning) and the audio sample. The function then does some magic, and spits out the new internal state1 and the output sample.
Now here's the crucial bit – what kind of magic the function does depends on the coefficient2 λ, which is not quite a constant: it depends both on what cutoff frequency we'd like the filter to have (this governs "how the filter will sound") and on what sample rate we're processing in. Unfortunately, the calculation of λ is a bit more complicated (lp1stCoeff $ 2*pi * (νᵥ ~*% δs) than the rest of the magic, so we wouldn't like having to do this for every single sample, all over again. Quite annoying, because νᵥ and δs are almost constant: they change very seldom, certainly not at each audio sample.
But currying saves the day! We simply calculate λ as soon as we have the necessary parameters. Then, at each of the many many audio samples to come, we only need to perform the remaining, very easy magic: yⱼ = yⱼ₁ + λ ⋅ (xⱼ - yⱼ₁). So we're being efficient, and still keeping a nice safe referentially transparent purely-functional interface.
1 Note that this kind of state-passing can generally be done more nicely with the State or ST monad, that's just not particularly beneficial in this example
2 Yes, this is a lambda symbol. I hope I'm not confusing anybody – fortunately, in Haskell it's clear that lambda functions are written with \, not with λ.
It's somewhat dubious to ask what the benefits of currying are without specifying the context in which you're asking the question:
In some cases, like functional languages, currying will merely be seen as something that has a more local change, where you could replace things with explicit tupled domains. However, this isn't to say that currying is useless in these languages. In some sense, programming with curried functions make you "feel" like you're programming in a more functional style, because you more typically face situations where you're dealing with higher order functions. Certainly, most of the time, you will "fill in" all of the arguments to a function, but in the cases where you want to use the function in its partially applied form, this is a bit simpler to do in curried form. We typically tell our beginning programmers to use this when learning a functional language just because it feels like better style and reminds them they're programming in more than just C. Having things like curry and uncurry also help for certain conveniences within functional programming languages too, I can think of arrows within Haskell as a specific example of where you would use curry and uncurry a bit to apply things to different pieces of an arrow, etc...
In some cases, you want to think about more than functional programs, you can present currying / uncurrying as a way to state the elimination and introduction rules for and in constructive logic, which provides a connection to a more elegant motivation for why it exists.
In some cases, for example, in Coq, using curried functions versus tupled functions can produce different induction schemes, which may be easier or harder to work with, depending on your applications.
I used to think that currying was simple syntax sugar that saves you a bit of typing. For example, instead of writing
(\ x -> x + 1)
I can merely write
(+1)
The latter is instantly more readable, and less typing to boot.
So if it's just a convenient short cut, why all the fuss?
Well, it turns out that because function types are curried, you can write code which is polymorphic in the number of arguments a function has.
For example, the QuickCheck framework lets you test functions by feeding them randomly-generated test data. It works on any function who's input type can be auto-generated. But, because of currying, the authors were able to rig it so this works with any number of arguments. Were functions not curried, there would be a different testing function for each number of arguments - and that would just be tedious.
A quick question, is there an operator in Haskell that works like the dollar sign but gives precedence to the left hand side. I.E. instead of
f (x 1)
being written as
f $ x 1
I'd like to write it as
x 1 $ f
This is purely a stylistic thing. I'm running a sequence of functions in order and it would be nice if I could write them left to right to match that I read left to right. If there an operator for this?
[update] A couple of people have asked if I can't define my own. In answer, I wanted to check there wasn't an existing operator before I reinvented the wheel.
As of GHC 7.10 (base 4.8.0.0), & is in Data.Function: https://hackage.haskell.org/package/base-4.8.0.0/docs/Data-Function.html
In Haskell you can use flip to change arguments' order of any binary function or operator:
ghci> let (|>) = flip ($)
ghci> 3 |> (+4) |> (*6)
42
I do not know, whether there is an standart operator, but what prevents you from writing your own? This works in ghci:
Prelude> let a $> b = b a
Prelude> 1 $> (+2)
3
Prelude> sum [1, 2] $> (+2)
5
Prelude> map (+2) [1, 2] $> map (+3)
[6,7]
UPDATE: searching on hoogle for a -> (a -> b) -> b (it is the type of this operator) found nothing useful.
This combinator is defined (tongue in cheek) in the data-aviary package:
Prelude Data.Aviary.BirdsInter> 1 `thrush` (+2)
Loading package data-aviary-0.2.3 ... linking ... done.
3
Although actually using that package is a rather silly thing to do, reading the source is fun, and reveals that this combinator is formed via the magic incantation of flip id (or, in ornithological parlance, cardinal idiot).
I am not aware of any standard version, but I've seen (#) used for that purpose in a couple places. The one in particular that comes to mind is HOC, which uses it in an idiom like:
someObject # someMessage param1 param2
I seem to recall seeing other "object-oriented" libraries using the # operator in the same way, but cannot remember how many or which ones.
Can't you just redefine $.
let ($) x f = f x
Or just choose a different operator, like $$