Let's see analyse code for factorial in Haskell using lambda function:
y f x = f (y f) x
factorial = y (\t n -> if n == 1 then 1 else n * t(n-1))
And I cannot understand how does it works. I know that it is connected with lambda calculus but nowadays I am not familiar with that so I have to understand without it or with minimal knowledge.
My doubt is:
What is f in definition of factorial? I mean this f: y f x = f (y f) x.
So what is f here? y (\t n -> if n == 1 then 1 else n * t(n-1))
Please explain me that, maybe expand recursion?
the fin factorial is the (\t n -> if n == 1 ...) lambda
y is a so called fix-point combinator and it's used to enable recursive definitions in the lambda-calculus (it applies f to it's argument again and again recursively)
to understand how it works you can just do some evaluation by hand:
factorial 3
= y (\t n -> ...) 3
{ def y and y (\t n -> ...) = factorial by eta-red. }
= (\t n -> ...) factorial 3
{ t = factorial, n = 3 -> else case }
= 3 * factorial 2
= 3 * (y (\t n -> ...) 2)
= 3 * ((\t n -> ...) factorial 2)
= { t = factorial, n = 2 -> else case }
= 3 * (2 * factorial 1)
= 3 * (2 * (y (\t n -> ...) 1))
= 3 * (2 * ((\t n -> ...) factorial 1)))
{ t = factorial n = 1 -> then case }
= 3 * (2 * 1)
= 6
y is the fixed-point combinator, also known as the y-combinator. In
factorial = y (\t n -> if n == 1 then 1 else n * t(n-1))
the lambda (\t n -> if n == 1 then 1 else n * t(n-1)) is bound to f in the definition of y. You can then do the expansion:
(\t n -> if n == 1 then 1 else n * t(n-1)) (y (\t n -> if n == 1 then 1 else n * t(n-1)))
so inside the lambda, t will be bound to the lambda itself, which allows it to call itself recursively.
Perhaps it's easier if you write out the y combinator thus, with two eta-expansions:
y :: ((a->b) -> a->b) -> a->b
y f x a = f (\q a' -> y f q a') x a
So f basically gets the recursive call (with a' in place of a) as its first argument.
Related
i am trying to write a power function in haskell that calculates f to the power of n, where f is a function itself, using function composition.
This is what I have so far:
let pow 0 f = (\x -> x)
pow n f = f . (pow (n-1) f)
in 2 ((\x -> x+1) 2)
I am expecting it to pass the function f(x)=x+1 to power function and return the square of the function. I try passing in the value 2 to the f(x) function, so i thought it would return 4
When I run it on haskell.org I get:
:: (Num a, Num (a -> t)) => t
Your line is invalid: 2 ((\x->x+1) 2) is malformed (as it is equivalent to 2 3).
let pow 0 f = (\x->x); pow n f = f.(pow (n-1) f) in (pow 2 (\x -> x + 1)) 2
does produce 4.
I tried all possible type declarations but I can't make this code even compile. The trick is in handling types for division. I tried Num a, Fractional a, Float a etc.
cube x = x * x * x
sum' term a next b =
if a > b
then 0
else term a + sum' term (next a) next b
integral f a b n = (h / 3) * (sum' term 0 succ n) where
h = (b - a) / n
y k = f $ a + (k * h)
term k
| k == 0 || k == n = y k
| odd k = 4 * y k
| even k = 2 * y k
main = do
print $ integral cube 0 1 100 -- 0.25
print $ (\x -> 3 * x * x) 1 3 100 -- 26
I isolated problem by deleting (/) function. This code compiles without any type declaration at all:
cube x = x * x * x
sum' term a next b =
if a > b
then 0
else term a + sum' term (next a) next b
integral f a b n = (sum' term 0 succ n) where
h = (b - a)
y k = f $ a + (k * h)
term k
| k == 0 || k == n = y k
| odd k = 4 * y k
| even k = 2 * y k
main = do
print $ integral cube 0 1 100
Another question is how to debug cases like this? Haskell's error messages doesn't help much, it's kind of hard to understand something like The type variable a0 is ambiguous or Could not deduce (a1 ~ a).
P. S. It's ex. 1.29 from SICP.
Update
Final answer is:
cube :: Num a => a -> a
cube x = x * x * x
sum' :: (Int -> Double) -> Int -> (Int -> Int) -> Int -> Double
sum' term a next b =
if a > b
then 0
else term a + sum' term (next a) next b
integral :: (Double -> Double) -> Double -> Double -> Int -> Double
integral f a b n = (h / 3) * sum' term 0 (+1) n where
h = (b - a) / n' where n' = fromIntegral n
y k = f $ a + (k * h)
term k
| k == 0 || k == n = y k'
| odd k = 4 * y k'
| even k = 2 * y k'
where k' = fromIntegral k
main = do
print $ integral cube 0 1 100 -- 0.25
print $ integral cube 0 1 1000 -- 0.25
print $ integral (\x -> 3 * x * x) 1 3 100 -- 26
/ is only used for types that are instances of Fractional, for Integral types use quot. You can use quot as an infix operator using backticks:
h = (b - a) `quot` n
The types of the two are
(/) :: Fractional a => a -> a -> a
quot :: Integral a => a -> a -> a
There are no types that are instances of both Fractional and Integral, which is why none of the type signatures would work. Unfortunately GHC doesn't know that it's impossible for a type to be an instance of both classes, so the error messages are not very intuitive. You get used to the style of GHC error messages though, and the detail they give helps a lot.
Also, as was suggested in the comments, I completely agree that all top level definitions should be given type signatures (including main). It makes error messages a lot easier to read.
Edit: Based on the comments below, it looks like what you want is something more like this (type signature-wise)
cube :: Num a => a -> a
sum' :: (Int -> Double) -> Int -> (Int -> Int) -> Int -> Double
integral :: (Double -> Double) -> Double -> Double -> Int -> Double
You will need to use fromIntegral to convert from Int to Double in h and in k. The type errors should be at least a bit more readable with these type signatures though.
I have the following function to obtain power of a matrix
X^0 = identity matrix,
X^1 =X;
X^2 = X'X;
X^3 = X X' X;
X^4 = X' X X' X ......
I tried with following function:
import Numeric.Container
import Numeric.LinearAlgebra
mpow :: Field t => (Matrix t) -> Integer -> (Matrix t)
mpow x 0 = ident $ cols x
mpow x 1 = x
mpow x n =
if (mod n 2) == 0 then
multiply (trans x) (mpow x $ n - 1)
else
multiply x (mpow x $ n - 1)
Is it possible to rewrite this function without using the if-else statement ?
Yes, you could use guards. But quite often it will compile into the same internal representation in Haskell.
import Numeric.Container
import Numeric.LinearAlgebra
mpow :: Field t => (Matrix t) -> Integer -> (Matrix t)
mpow x 0 = ident $ cols x
mpow x 1 = x
mpow x n | (mod n 2) == 0 = multiply (trans x) (mpow x $ n - 1)
| otherwise = multiply x (mpow x $ n - 1)
As freyrs mentioned, guards and if statements are exactly equivalent as they are both converted to case of when you compile your code. But, you can still get rid of them:
mpow' :: Field t => (Matrix t) -> Integer -> (Matrix t)
mpow' x 0 = ident $ cols x
mpow' x 1 = x
mpow' x n = multiply (head (drop n' fs) $ x) (mpow' x $ n - 1)
where fs = [trans, id]
n' = fromInteger (mod n 2)
However, this isn't more concise, nor does it better communicate what your function is doing to the reader. So don't do this, unless you really hate conditionals.
How do I write
f 0 = 1
f x = (f(x-1))*2 + 2
as a lambda in Haskell?
Thanks in anticipation.
You'd move the pattern matching from the right and use a case expression
f = \ x -> case x of
0 -> 1
x -> f (x-1) * 2 + 1
f = \x -> if x == 0 then 1 else (f (x - 1)) * 2 + 2
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).