How to sum a number in a list - haskell

My question is :
I have a list and a number and I want to sum the number to the list so I can do this
Adding ls n = [x+n| x<-ls]
and it works.
My question is I want to add n+1, n+2, n+3 depending of the length of the list.
If I do
let b = 0
Adding´ ls n = [x+adder n b| x<-ls] where adder n b= n+b,b++
it doesn't work because the b doesn't advance, so if I have Adding´ [1,3,4] 3 = [4,7,9] .

You may use Data.List.mapAccumL (mapAccumL :: Traversable t => (a -> b -> (a, c)) -> a -> t b -> (a, t c)) to achieve this task.
The first parameter is a function which takes two parameters a (accumulator) and n (the list item) and returns a tuple. In our case we increment a (the accumulator) by 1 and map the current element n by adding the accumulator. The result is a tuple in which the first item is the final state of the accumulator and the second is the final state of the list. We extract the second item by snd.
Prelude> snd $ Data.List.mapAccumL (\a n -> (a+1,n+a)) 3 [1,3,4]
[4,7,9]

Approach the problem recursively. Add a number to the first element of the list, then recurse on the tail of the list with the next larger number. Repeat until you are out of numbers. Instead of incrementing b, you start a new function call in which b has a larger value.
adding [] _ = []
adding (x:xs) b = x + b : adding xs (b+1)
As an example, consider
adding [7, 10, 7, 5] 0 == 7 + 0 : adding [10, 7, 5] 1
== 7 : (10 + 1 : adding [7, 5] 2)
== 7 : 11 : (7 + 2 : adding [5] 3)
== 7 : 11 : 9 : (5 + 3 : adding [] 4)
== 7 : 11 : 9 : 8 : []
== [7, 11, 9, 8]
You can replace 0 with any starting value n in the initial call; the recursive call always increments it.

Related

What is the meaning of `sum [] = 0`?

sum :: [Int] -> Int
sum [] = 0
sum (x:xs) = x + sum xs
I do not understand what the purpose of the line sum [] = 0 is. I found this piece of code in a textbook (it did not go into detail as to what this line does.)
sum [] = 0 is the edge condition of the recursion.
Suppose we have sum [1, 4, 6, 8]. The list can be rewritten as 1:4:6:8:[]. The empty list is the last 'element'. The calculation is as follow (1 + ( 4 + (6 + ( 8 + 0)))). When all the elements of the list have been traversed, what remains is the empty list. Adds zero to the calculated result and ends the iteration.

Haskell foldl1 how does it work?

I have a code
g :: Int->Int->Int
g x y = x*2 - y
then If i call foldl1 g [4,3,2,1] it returns 15, but i don't get how it returns 15, can anyone explain me why this is the case?
foldl1 first applies the function to the first two elements of the list, then takes the result and applies the function to it and the third element, then takes the result and applies the function to it and the fourth element, then to result and fifth element, then sixth element, and so on until the list ends.
So:
Step 1: g 4 3 = 4*2 - 3 = 5
Step 2: g 5 2 = 5*2 - 2 = 8
Step 3: g 8 1 = 8*2 - 1 = 15

Haskell Hermite polynomials implementation

Haskell allows to represent recurrent functions in a very concise way. For example, infinite list, that contains Fibonacci numbers can be defined as follows:
fibs :: [Integer]
fibs = 1 : 1 : zipWith (+) fibs (tail fibs)
I am dealing with 'probabilists' Hermite polynomials, which have the following recursion relation:
What would be the optimal way to construct the infinite list of n-th Hermite polynomials for given x?
We can write it as:
hermite :: (Enum n, Num n) => n -> [n]
hermite x = s
where s#(_:ts) = 1 : x : zipWith3 (\hn2 hn1 n1 -> x*hn1 - n1*hn2) s ts [1..]
where the first items 1 : x : ... are the first elements of the hermite (you can fill in other values).
For the next one, we zip the original values s (so that starts with H0), the tail ts of s (that starts with H1) and the index (that starts with 2, 3, ...) and perform an operation x*hn1 - x*hn2 (nh1 stands for Hn-1, and nh2 stands for Hn-2), and so we calculate the next element each time.
The first 11 values for x = 0.75 are:
Prelude> take 11 (hermite 0.75)
[1.0,0.75,-0.4375,-1.828125,-5.859375e-2,7.2685546875,5.744384765625,-39.30303955078125,-69.68797302246094,262.1583366394043,823.8105096817017]
So the first value is 1, the second x, the third one x*x-2, the fourth one x*x*x-2*x-3*x, and so on.
That being said, if I recall correctly, the recursion formula of the Hermite polynomials is:
Hn(x) = 2×x×Hn-1(x)-2×(n-1)Hn-2(x)
instead of the one quoted in the question.
In that case the formula is thus:
hermite :: (Enum n, Num n) => n -> [n]
hermite x = s
where s#(_:ts) = 1 : 2 * x : zipWith3 helper s ts [1..]
helper hn2 hn1 n1 = 2 * (x * hn1 - n1 * hn2)
Then the first 11 values are:
Prelude> take 11 (hermite 0.75)
[1.0,1.5,0.25,-5.625,-9.9375,30.09375,144.515625,-144.3515625,-2239.74609375,-1049.994140625,38740.4384765625]
Which is correct acording to this Wolfram article:
H0 = 1
H1 = 2*x
H2 = 4&dot;x2 - 2
H3 = 8&dot;x3 - 4&dot;x
H4 = 16&dot;x4 - 48&dot;x2 + 12
Which maps exactly on the values we obtained:
Prelude> let x = 0.75 in [1,2*x,4*x*x-2,8*x*x*x-4*x,16*x*x*x*x-48*x*x+12]
[1.0,1.5,0.25,0.375,-9.9375]

find outmost evaluation (Haskell)

I have some Haskell code and need to write down Leftmost-innermost (call by value) and outermost (call-by-name):
second :: [Int] -> Int
second [] = 0
second (_:[]) = 0
second (_:x:xs) = x
doubleEach :: [Int] -> [Int]
doubleEach [] = []
doubleEach (x:xs) = x * 2 : (doubleEach xs)
repeat :: Int -> Int -> [Int]
repeat x n = if n > 0 then x : (repeat x (n-1)) else []
repeat ( second (doubleEach [2,3,5] )) ( second [3, 1, 4] )
innermost (call-by-value):
1. repeat (second (doubleEach [2,3,5] )) (second [3,1,4])
2. repeat (second 4 : doubleEach [3,5])) (1)
3. repeat (second (4 : 6 : d [5])) (1)
4. repeat (second ( 4 : 6 : 10 )) (1)
5. repeat (6) (1)
6. [6]
Question: How can I get outermost (call-by-name) stept by step evaluation? I do not understand how I can do that if repeat needs specified values to work and they are not given until the inner part is not evaluated.
How can I get outermost (call-by-name) stept by step evaluation? I do not understand how I can do that if repeat needs specified values to work and they are not given until the inner part is not evaluated.
You don't need the values to expand the function call - you can just pass in the unevaluated expressions. And then you only evaluate those expressions when it's necessary for ifs, pattern matches or primitive functions. That's how call-by-name evaluation works.
So your first step would be to take the body of repeat, replace each occurrence of x with second (doubleEach [2,3,5]) and each occurrence of n with second [3, 1, 4]. Then you'll need to evaluate the if condition and then you proceed with the body of the if.

Understanding Haskell's fibonacci

fibs :: [Int]
fibs = 0 : 1 : [ a + b | (a, b) <- zip fibs (tail fibs)]
This generates the Fibonacci sequence.
I understand the behaviour of the guards, of :, zip and tail, but I don't understand <-. What is it doing here?
Due to the upvotes I made my comment into an answer.
What you see is not a guard but it is list comprehension. For starters think of it as a way to express a mathematical set notation like A = { x | x element N } which means something along the lines of: The set A is the set of all natural numbers. In list comprehension that would be [x | x <- [1..] ].
You can also use constraints on your numbers: [x | x <- [1..], x `mod` 2 == 0 ] and many other things.
There are alot of good haskell turorials out there that cover list comprehension and even a StackOverflow question regarding haskell resources.
The only tricky thing is the zip fibs (tail fibs). zip just makes a pairwise list from each of its arguments. So if you have two lists like this:
[ 1, 2, 3, 4 ]
[ "a", "b", "c", "d" ]
Zipping them will make:
[ (1,"a"), (2,"b"), (3,"c"), (4,"d") ]
The left arrow (assignment into a destructuring pattern) just extracts the paired elements so they can be added together. The two lists being zipped are fibs and (tail fibs) -- in other words, the Fibonacci sequence, and the Fibonacci sequence offset by 1 element. Haskell is lazily-evaluated, so it can calculate the list to however many elements are required. This applies to zip as well.
One advantage of functional programming is that you can evaluate an expression by hand like it is a math problem:
fibs = 0 : 1 : [ a + b | (a, b) <- zip fibs (tail fibs)]
= 0 : 1 : [ a + b | (a, b) <- zip [0, 1, ??] (tail [0, 1, ??])]
Here the ?? is the part which has not yet been evaluated. We will fill it in as we proceed.
= 0 : 1 : [ a + b | (a, b) <- zip [0, 1, ??] [1, ??])]
= 0 : 1 : [ a + b | (a, b) <- (0, 1) : zip [1, ??] [??]]
Note that I am eliding the evaluation of zip since its definition is not given here and the details are not really germane to the current question. This is the notation I will use to show each pair of numbers is created by zip and consumed by the list comprehension.
= 0 : 1 : 0+1 : [ a + b | (a, b) <- zip [1, ??] [??]]
= 0 : 1 : 1 : [ a + b | (a, b) <- zip [1, ??] [??]]
Now we know that the next element in the ?? is a 1:
= 0 : 1 : 1 : [ a + b | (a, b) <- zip [1, 1, ??] [1, ??]]
= 0 : 1 : 1 : [ a + b | (a, b) <- (1, 1) : zip [1, ??] [??]]
= 0 : 1 : 1 : 1+1 : [ a + b | (a, b) <- zip [1, ??] [??]]
= 0 : 1 : 1 : 2 : [ a + b | (a, b) <- zip [1, ??] [??]]
And the next element is a 2:
= 0 : 1 : 1 : 2 : [ a + b | (a, b) <- zip [1, 2, ??] [2, ??]]
Rinse and repeat.
Let's expand it out.
zip creates pairs out of the contents of two lists. So the first pair zip fibs (tail fibs) gives us is (0, 1), which adds up to 1. So now the list is [0,1,1]. We now know three elements in the list, so the list comprehension can continue, grabbing the next item from the list and the next item from the tail, which gives (1,1) — added together, making 2. Then we get the next pair, which is (1,2), making the next number in the sequence 3. This can continue infinitely, since the comprehension will always provide enough items.
For what it's worth, I find the following version easier to understand:
fibs = 0 : 1 : zipWith (+) fibs (tail fibs)
The list comprehension in the brackets:
[ a + b | (a, b) <- zip fibs (tail fibs)]
returns a list containing the output (a + b) where the variables a and b come from the result of
zip fibs (tail fibs)
The key concept here is lazy evaluation which means that if the value is right there then take it without further computing say that i have got the value and the job is done, i don't need to compute future value temporary now. and if the value is not available then just compute it and of course it's lazy so it won't bother computing next needed value.
i write another implementation to illustrate this and use ?? to be a value placeholder which needs to be computed if needed.
fibs = 1:1:[ y!!1 + y!!0 | x<-[2..], y <- [[last (take x fibs), last (take (x-1) fibs)]] ]
i use x to indicate number of available values in fibs (which doesn't need to be computed again) and y to be a [[last fib values]] nested list. its inner list contains last two values of available values in fibs.
so here is the process of the computation:
x == 2, so y is [last (take 2 fibs), last (take 1 fibs)]. lazy evaluation lets us just take available values and don't bother worrying values in the future. it tells me to take first 2 and 1 values of fibs and the values are right there 1,1 and 1. y now is [last [1,1], last [1]] which is [1,1] and to get final value it need to compute y!!1 + y!!0. That's obvious and final value is 2. so now fibs is [1, 1, 2, ??].
x == 3, just the same as step 1. y is [last [take 3 fibs], last [take 2 fibs]] which is [last [1,1,2], last [1,1]], the value now is available so we can just take it and go on. Finally, we got the fourth value 3.
that's it, just repeat the above steps and you can get all values even it is infinite
Doesn't it seems familiar? just like using a recursive function to compute fibs. we now let compiler itself to do the stuff(referring). we use the lazy evaluation here.
the zip implementation is just another representation of [last fibs values] here. you just need a little modification to understand the zip version of fibs implementation.
haskell wiki: lazy evaluation
for <- symbol: List comprehension
I prefer the more general
fib = 1 : [ x + y | (x, y) <- zip fib (0 : fib) ]
This most closely models how one understands the Fibonacci sequence in terms of generating functions. If f(n) = 0 for n < 0, f(0) = 1, and f(n) = a*f(n-1) + b*f(n-2) for n > 0, then we'd like to be able to write the single line
f(n) = 1_0 + a*f(n-1) + b*f(n-2)
and have the reader know what we mean. Unfortunately, this requires some unstated conventions to make sense.
Using the generating function g(t) = f(0) + f(1)t + f(2)t^2 + ... we can write the equation
g(t) = 1 + a t g(t) + b t^2 g(t)
which easily solves for g(t) in closed form as
g(t) = 1 / (1 - a t - b t^2)
The Haskell code
g = 1 : [ a*x + b*y | (x, y) <- zip g (0 : g) ]
implements this same equation.
It defines this stream diagram,(*)
.---->>---->>----.
/ \
<---- 0 <---- 1 ----<<--- (+)
\ /
*--->>---*
that pulls new input from itself as it is produced, but always by one and two positions behind the production point, maintaining the two "back pointers" into the sequence as it were, one position apart.
This is reflected in the definition,
-- .------->>------>>---.
-- / \
fibs = 0 : 1 : [ a + b | a <- fibs
{- \ -} | b <- tail fibs]
-- \ /
-- *-->>------>>---*
with parallel list comprehensions (:set -XParallelListComp etc.).
Since it only uses its last two elements, it is equivalent to
map fst . iterate (\(a, b) -> (b, a+b)) $ (0,1)
(*) The execution of this diagram proceeds as follows:
.---->>---->>----.
/ \ 0
? <---- 0 <---- 1 ----<<--- (+)
\ / 1
*--->>---*
.---->>---->>----.
/ \ 1
0,? <---- 1 <---- 1 ----<<--- (+)
\ / 1
*--->>---*
.---->>---->>----.
/ \ 1
0,1,? <---- 1 <---- 2 ----<<--- (+)
\ / 2
*--->>---*
.--->>---->>----.
/ \ 2
0,1,1,? <--- 2 <--- 3 ----<<--- (+)
\ / 3
*--->>---*
.--->>--->>---.
/ \ 3
0,1,1,2,? <--- 3 <-- 5 ---<<--- (+)
\ / 5
*--->>---*
......

Resources