Why does the following simple Haskell function give slightly strange answers? - haskell

(%?) :: Int -> (Int -> Int) -> Int
x %? f = f x
m :: Int -> Int
m v = v %? \z -> z * 2 %? \z -> z + 3 %? \x -> x + z
or simpler
p :: Int -> Int
p v = v %? \z -> z * 2 %? \z -> z + 3
e.g, p 4 = 20

Well, it would help to know what you were expecting it to do. But perhaps it would help to put some explicit parentheses in p:
q :: Int -> Int
q v = v %? (\z -> z * (2 %? (\z -> z + 3)))
Perhaps you were you expecting something more like this:
p2 :: Int -> Int
p2 v = v %? (\z -> (z * 2) %? (\z -> z + 3))
It's probably a good idea to add an infix declaration for any operators you declare, to avoid this sort of confusion. Arithmetic operators have mid-high precedence, but given what the function does you probably want very low precedence anyway.
As an aside--lambdas extend all the way to the right, but I'm guessing that's not what's tripping you up.

%? has too high precedence and is left-associative, so v %? \z -> z * 2 %? \z -> z + 3 is the same as v %? \z -> z * (2 %? \z -> z + 3).
If you want %? to behave like $ use infixr 0 %?, so it has the same precedence and associativity as $.

Related

Currying in Haskell with 2+ arguments

I'm starting to learn Haskell so I need to understand currying also (it's the first time I've seen this technique too). I think I get how it works in some cases where the currification only "eliminates" one of the parameters. Like in the next example where I'm trying to calculate the product of 4 numbers.
This is the uncurried function:
prod :: Integer->Integer->Integer->Integer->Integer
prod x y z t = x * y * z * t
This is the curried function:
prod' :: Integer->Integer->Integer->Integer->Integer
prod' x y z = (*) (x*y*z)
But I don't understand how could I continue this dynamic and do for example the same function with only two arguments and so on:
prod'' :: Integer->Integer->Integer->Integer->Integer
prod'' x y =
This is the uncurried function:
prod :: Integer -> Integer -> Integer -> Integer -> Integer
prod x y z t = x * y * z * t
This is already a curried function. In fact all functions in Haskell are automatically curried. Indeed, you here wrote a function that looks like:
prod :: Integer -> (Integer -> (Integer -> (Integer -> Integer)))
Haskell will thus produce a function that looks like:
prod :: Integer -> (Integer -> (Integer -> (Integer -> Integer)))
prod = \x -> (\y -> (\z -> (\t -> x * y * z * t)))
Indeed, we can for example generate such function:
prod2 = prod 2
This will have type:
prod2 :: Integer -> (Integer -> (Integer -> Integer))
prod2 = prod 2
and we can continue with:
prod2_4 :: Integer -> (Integer -> Integer)
prod2_4 = prod2 4
and eventually:
prod2_4_6 :: Integer -> Integer
prod2_4_6 = prod2_4 6
EDIT
The function prod' with:
prod'' x y = (*) ((*) (x*y))
Since that means you multiply (*) (x*y) with the next parameter. But (*) (x*y) is a function. You can only multiply numbers. Strictly speaking you can make functions numbers. But the Haskell compiler thus complains that:
Prelude> prod'' x y = (*) ((*) (x*y))
<interactive>:1:1: error:
• Non type-variable argument in the constraint: Num (a -> a)
(Use FlexibleContexts to permit this)
• When checking the inferred type
prod'' :: forall a.
(Num (a -> a), Num a) =>
a -> a -> (a -> a) -> a -> a
It thus says that you here aim to perform an operation with a function a -> a as first operand, but that this function is not an instance of the Num typeclass.
What you have is
prod x y z t = x * y * z * t
= (x * y * z) * t
= (*) (x * y * z) t
Hence by eta reduction (where we replace foo x = bar x with foo = bar)
prod x y z = (*) (x * y * z)
= (*) ( (x * y) * z )
= (*) ( (*) (x * y) z )
= ((*) . (*) (x * y)) z
so that by eta reduction again,
prod x y = (*) . (*) (x * y)
Here (.) is the function composition operator, defined as
(f . g) x = f (g x)
What you're asking about is known as point-free style. "Point-free" means "without explicitly mentioning the [implied] arguments" ("point" is a mathematician's jargon for "argument" here).
"Currying" is an orthogonal issue, although Haskell being a curried language makes such definitions -- and partial application ones, shown in Willem's answer -- easier to write. "Currying" means functions take their arguments one at a time, so it is easy to partially apply a function to a value.
We can continue the process of pulling the last argument out so it can be eliminated by eta reduction further. But it usually rapidly leads to more and more obfuscated code, like prod = ((((*) .) . (*)) .) . (*).
That's because written code is a one-dimensional encoding of an inherently two-dimensional (or even higher-dimensional) computational graph structure,
prod =
/
*
/ \
*
/ \
<-- *
\
You can experiment with it here. E.g., if (*) were right-associative, we'd get even more convoluted code
\x y z t -> x * (y * (z * t))
==
(. ((. (*)) . (.) . (*))) . (.) . (.) . (*)
representing just as clear-looking, just slightly rearranged, graph structure
/
<-- *
\ /
*
\ /
*
\

How to fix "Illegal type signature" error in Haskell

I ran into the following error in Haskell:
"Type signatures are only allowed in patterns with ScopedTypeVariables"
How should I re-use the defined variables. Thanks in advance
sum :: (Double -> Double) -> (Double -> Double) -> Int ->
(Double -> Double)
sum f g n = (\x -> helper f g n x)
where
helper :: (Double -> Double) -> (Double -> Double) -> Int -> Double ->
Double
|n == 0 = 0
|mod n 2 == 1 = f(x) + helper f g n-1 f(x)
|otherwise = g(x) + helper f g n-1 g(x)
This actually looks more like a syntactical error: you never defined a function body for helper, indeed you defined the signature of helper, followed by guards (the | ... part), but you should again state helper f g n x = ....
Furthermore I don't think it is useful to define helper here with a variable for f, an g, since these remain fixed throughout the recursion.
You can probably define the function as:
sumfg :: (Double -> Double) -> (Double -> Double) -> Int -> Double -> Double
sumfg f g = helperf
where helperf 0 _ = 0
helperf i x = let fx = f x in fx + helperg (i-1) fx
helperg 0 _ = 0
helperg i x = let gx = g x in gx + helperf (i-1) gx
We here defined two "helper" functions helperf and helperg, helperf will sum up f x with helperg (i-1) (f x), and helperg does the same, except that we use g instead of f. We here thus use mutual recursion to solve the problem.
We can however solve this problem more elegantly, by making use of scanl :: (b -> a -> b) -> b -> [a] -> [b], take :: Int -> [a] and sum :: Num a => [a] -> a:
sumfg :: Num a => (a -> a) -> (a -> a) -> Int -> a -> a
sumfg f g n x = sum (take n (scanl (flip ($)) (f x) (cycle [g, f])))
Here we thus make an infinite list of g and f, like [g, f, g, f, g, f, ...] with cycle [f, g]. We then use scanl (flip ($)) to each time apply the accumulator to one of the functions, and yield that element. We take the first n items of that list with take n, and finally we use sum to sum up these values.
For example:
Prelude> sumfg (2+) (3*) 5 1
91
Since (2+1) + (3*(2+1)) + (2+(3*(2+1))) + (3*(2+(3*(2+1)))) + (2+(3*(2+(3*(2+1))))) is 91.
We also generalized the signature: we can now work with any numerical type a, with the two functions f and g of type f, g :: a -> a.

Haskell `let` bindings in lambda calculus

I want to understand how let bindings work in Haskell (or maybe lambda calculus, if the Haskell implementation differs?)
I understand from reading Write you a Haskell that this is valid for a single let binding.
let x = y in e == (\x -> e) y
This makes sense to me, since it's consistent with how bindings work in the lambda calculus. Where I'm confused is using multiple let bindings, where one binding can reference the bindings above. I will provide a trivial example.
Original code:
let times x y = x * y
square x = times x x
in square 5
My guess at the implementation:
(\square times -> square 5) (\x -> times x x) (\x -> x * x)
This seems not to work because times is not defined when square is called by the lambda. However, this can by solved by this implementation:
(\square -> square 5) ((\times x -> times x x) (\x -> x * x))
Is this the proper way to implement this binding, at least in the lambda calculus?
The times/square example can be expressed in terms of lambda functions using scoping:
(\times -> (\square -> square 5)(\x -> times x x))(\x y -> x * y)
But scoping isn't enough for recursive or mutually recursive let-bindings like
let ones = 1 : ones in take 5 ones
let even n = n == 0 || odd (abs n - 1)
odd n = n /= 0 && even (abs n - 1)
in even 7
In the lambda calculus you can define the y-combinator for recursion as
(\f -> (\x -> f (x x))(\x -> f (x x)))
This lets you define functions and values in terms of themselves. That formulation isn't legal haskell due to typing constraints but there are ways around that.
Using the y-combinator lets us express the above let-bindings using the lambda calculus:
(\ones -> take 5 ones)((\f -> (\x -> f (x x))(\x -> f (x x)))(\ones -> 1 : ones))
(\evenodd -> evenodd (\x y -> x) 7)((\f -> (\x -> f (x x))(\x -> f (x x)))(\evenodd c -> c (\n -> n == 0 || evenodd (\x y -> y) (abs n - 1)) (\n -> n /= 0 && evenodd (\x y -> x) (abs n - 1))))
Note that multiple let bindings can be reduced to a single one, defining a pair (tuple, in the general case). E.g. we can rewrite
let times x y = x * y
square x = times x x
in square 5
as
let times = \x y -> x * y
square = \x -> times x x
in square 5
then
let (times, square) = (\x y -> x * y, \x -> times x x)
in square 5
then, if wanted,
let pair = (\x y -> x * y, \x -> fst pair x x)
in snd pair 5
After that, we can apply the usual lambda calculus translation. If the pair definition ends up to be recursive, as in the case above, we need a fixed point combinator.
(\pair -> snd pair 5) (fix (\pair -> (\x y -> x * y, \x -> fst pair x x)))
Note that this translation does not play along type inference algorithms, which handle let in a special way, introducing polymorphism. This is not important if we only care about the dynamic aspects of our program, though.
I will answer my own question to maybe provide a helpful perspective to those who visit this question.
We want to implement the following program with two let bindings:
let times a b = a * b
square x = times x x
in square 5
To start with, let's simplify this to the essence of what we want:
square 5
Simple enough. However, square in this case is undefined! Well, we can bind it using the mechanism our language provides us with - a lambda. This gives us (\ square -> square 5) (\x -> times x x). Now square is defined, but its cousin times is not... Well, we need another lambda! Our final program should look like this:
(\times -> (\square -> square 5) (\x -> times x x)) (\a b -> a * b)
Notice that the (\times -> ...) completely encloses our last step, so that times will be in scope as it is bound. This is consistent with the answer given by #rampion, and reduces as follows:
(\times -> (\square -> square 5) (\x -> times x x)) (\a b -> a * b) =>
(\square -> square 5) (\x -> (\a b -> a * b) x x) =>
(\square -> square 5) (\x -> (\b -> x * b) x) =>
(\square -> square 5) (\x -> x * x) =>
(\x -> x * x) 5 =>
5 * 5 =>
25
If the square function had not depended on times, we could have easily written (\times square -> ..... The dependency means that we must nest these two environments, one containing times, and another inside of that which can use its definition.
Thanks for all of your help! I'm blown away by the simplicity and power of the lambda calculus.

Writing Category Instance for custom Lens

I have been reading this article for understanding Lenses. I know this is different from
Edward Knett's lens package, but nonetheless it's useful for fundamentals.
So, A Lens is defined like this:
type Lens a b = (a -> b, b -> a -> a)
It has been mentioned that Lenses form a category and I have been
trying out to create an instance for Category typeclass. For a start, I
wrote the type definition for the functions:
(.) :: Lens y z -> Lens x y -> Lens x z
id :: Lens x x
And after this, I just stare it for all day. What exactly is the
thought process for writing it's definition?
I found this article (Lenses from Scratch on fpcomplete by Joseph Abrahamson) to be very good, it starts from the same representation of lenses you started with, defines composition for it and continues along the path to a representation more similar to lens
EDIT: I find type holes to be excellent when doing this kind of things:
(<.>):: Lens y z -> Lens x y -> Lens x z
(getA,setA) <.> (getB,setB) = (_,_)
So now we have 2 holes, the first in the tuple says (output cleaned):
Found hole ‘_’ with type: x -> z
...
Relevant bindings include
setB :: y -> x -> x
getB :: x -> y
setA :: z -> y -> y
getA :: y -> z
(<.>) :: Lens y z -> Lens x y -> Lens x z
Looking hard at the bindings, we already have what we need! getB :: x -> y and getA :: y -> z together with function composition (.) :: (b -> c) -> (a -> b) -> a -> c
So we happily insert this:
(<.>):: Lens y z -> Lens x y -> Lens x z
(getA,setA) <.> (getB,setB) = (getA . getB, _)
And continue with the second type hole, which says:
Found hole ‘_’ with type: z -> x -> x
Relevant bindings include
setB :: y -> x -> x
getB :: x -> y
setA :: z -> y -> y
getA :: y -> z
The most similar thing we have is setA :: z -> y -> y, we start by inserting a lambda, capturing the arguments:
(getA,setA) <.> (getB,setB) = (getA . getB, \z x -> _)
changing your type hole to:
Found hole ‘_’ with type: x
Relevant bindings include
x :: x
z :: z
setB :: y -> x -> x
getB :: x -> y
setA :: z -> y -> y
getA :: y -> z
we could insert x which type checks, but does not give us what we want (nothing happens when setting). The only other binding that could give us an x is setB, so we insert that:
(getA,setA) <.> (getB,setB) = (getA . getB, \z x -> setB _ _)
Our first type hole says:
Found hole ‘_’ with type: y
Relevant bindings include
x :: x
z :: z
setB :: y -> x -> x
getB :: x -> y
setA :: z -> y -> y
getA :: y -> z
So we need an y, looking at what is in scope, getB can give us a y if we give it a x, which we happen to have, but this would lead us to a useless lens doing nothing again. The alternative is to use setA:
(getA,setA) <.> (getB,setB) = (getA . getB, \z x -> setB (setA _ _) _)
(Speeding things a little up from here on)
Again the first hole wants something of type z which he happen to have as an argument to our lambda:
(getA,setA) <.> (getB,setB) = (getA . getB, \z x -> setB (setA z _) _)
To fill the first type hole of type y we can use getB :: x -> y giving it the argument of our lambda:
(getA,setA) <.> (getB,setB) = (getA . getB, \z x -> setB (setA z (getB x)) _)
Which leaves us with one remaining type hole, which can trivially be replaced by x, leading to the final definition:
(<.>):: Lens y z -> Lens x y -> Lens x z
(getA,setA) <.> (getB,setB) = (getA . getB, \z x -> setB (setA z (getB x)) x)
You can try to define id for yourself, using type holes and hoogle if necessary
Try this:
(.) :: Lens y z -> Lens x y -> Lens x z
(getZfromY , setZinY) . (getYfromX , setYinX) = (getZfromX , setZinX)
where getZfromX someX = ...
setZinX someZ someX = ...
The idea is: combine the two getters to make the new getter, and combine the two setters to make a new setter.
For the identity, think about:
id :: Lens x x
id = (getXfromX , setXinX)
where getXfromX someX = ...
setXinX newX oldX = ...
It seems to be a fairly straighforward process. But also need to check that you get a category - this requires equational reasoning - because, for example, there is at least one more way to implement the setter of id with type x->x->x - only one of those will make a category.
So, let's start with getting functions of the right type.
Lens y z -> Lens x y -> Lens x z ==
(y->z, z->y->y) -> (x->y, y->x->x) -> (x->z, z->x->x)
It seems clear how to get x->z from x->y and y->z - compose. Well, and you have ways to construct new x from old x and new y, and a way to get old y from old x, so if you can construct new y from z and old y, you are done.
(.) (yz, zyy) (xy, yxx) = (yz . xy, \z x -> yxx (zyy z (xy x)) x)
Similarly for id:
Lens x x ==
(x->x, x->x->x)
So
id = (id, const)
So far so good, the types check. Now let's check that we've got a category. There is one law:
f . id = f = id . f
Checking one way (a bit informal, so need to bear in mind that . and id refer to different things in f . id and fg . id):
f . id = (fg, fs) . (id, const) =
(fg . id, \z x -> const (fs z (id x)) x) =
(fg, \z x -> fs z (id x)) = (fg, fs)
Checking the other way:
id . f = (id, const) . (fg, fs) =
(id . fg, \z x -> fs (const z (fg x)) x) =
(fg, \z x -> fs z x) = (fg, fs)

What does the following lambda function in Haskell actually return?

Consider the following lambda function in Haskell:
(\x g n -> g (x * n))
It takes two parameters: a Num named x and a function g which takes a Num named n and returns something else. The lambda function returns another function of the same type as g:
(\x g n -> g (x * n)) :: Num a => a -> (a -> t) -> a -> t
What I don't understand is what does the expression g (x * n) actually represent. For example consider the following use case:
((\x g n -> g (x * n)) 2 id)
In this case x is 2 and g is id. However what is n? What does g (x * n) represent? By simple substitution it can be reduced to id (2 * n). Is this the same as id . (2 *)? If so then why not simply write (\x g -> g . (x *))?
I'm going to contradict chirlu. (\x g n -> g (x * n)) is a function of one argument.
Because all functions only take one argument. It's just that that function returns another function, which returns another function.
Desugared, it's the same as
\x -> \g -> \n -> g (x * n)
Which is pretty close to its type
Num a => a -> (a -> b) -> a -> b
Expanding your use case:
(\x g n -> g (x * n)) 2 id
Let's expand that
(\x -> \g -> \n -> g (x * n)) 2 id
Which is the same as
((\x -> \g -> \n -> g (x * n)) 2) id
Now we can apply the inner function to its argument to get
(let x = 2 in \g -> \n -> g (x * n)) id
or
(\g -> \n -> g (2 * n)) id
Now we can apply this function to its argument to get
let g = id in \n -> g (2 * n)
or
\n -> id (2 * n)
Which, via inspection, we can state is equivalent to
\n -> 2 * n
Or, point-free
(2*)
You're close. The last example you gave, ((\x g n -> g (x * n)) 2 id) represents a partial application of the function. It has a type signature of Num a => a -> t and is equivalent to the following: \n -> id (2 * n).

Resources