Adding the powers of numbers in haskell with foldl - haskell

I am being asked to make an haskell function that computes something like
1^2 + 2^2 + 3^2 ...
While I find it quite easy to implement with list comprehensions
sum [ k^2 | k <- [1..100]]
or maps
sum (map (\x -> x*x) [1..100])
I'm having some hard time getting how to achieve it with foldls.
If I am not wrong, one needs no less than 3 parameters in a recursive function to achieve a result with this:
The current position (1... up to n)
The current sum
Where to stop
Even if I define this function, it will still return a tuple, not a number (like I need it to!).
Could anyone be kind enough to give me some clues on what I may be missing?
Thanks

If you look at the definition of sum, it's just sum = foldl (+) 0. So if you replace sum with foldl (+) 0 in either of your solutions, you have a solution using foldl.
You can also get rid of the need for list comprehensions or map by using foldl with a function that adds the square of its second argument to its first argument.
I'm not sure where your considerations about recursive functions figure into this. If you're using foldl, you don't need to use recursion (except in so far that foldl is implemented using recursion).
However, you are wrong that a recursive function would need three arguments: A recursive functions summing the squares of each element in a list, would most straight-forwardly implemented by taking a list and adding the head of the list to the result of calling the function on the list's tail. The base case being squareSum [] = 0. This has nothing to with foldl, though.

The "current position" (actually the next item in the list, just like in your map and list comprehension versions) and where to stop are implicit in the list being folded over. The current sum is the "accumulator" parameter of the fold. So, fill in the blank:
foldl (\runningSum nextNumber -> ____) 0 [1..100]

Related

Permutations in Haskell involving List Comprehensions, Recursion and the delete function

I'm a Haskell beginner following exercises from a book. The first question asked me to define a function that deletes the first occurrence of an integer from a list of integers.
E.g.
delete 5 [1,5,3,5,1]
outputs:
[1,3,5,1]
The second question asks me to create a function that uses the delete function I just defined, that takes as an argument a list of integers, and outputs a list of all the permutations as lists.
E.g.
perms [1,2,3]
outputs:
[[1,2,3],[1,3,2],[2,1,3],[2,3,1],[3,1,2],[3,2,1]]
I tried hard, gave up and googled the solution.
Here's what I found:
perms [] = [[]]
perms xs = [ i:j | i <- xs, j <- perms $ delete i xs ]
I looked around and found many other similar solutions, almost identical, just using different variable names and parentheses instead of the $ symbol, so I'm guessing this is a common problem with an idiomatic solution.
I'm just a little lost trying to understand exactly what this code is doing. I am seeking a step by step explanation through the recursion, to understand how this code is creating a list of permutations?
Like any recursive function that operates on lists, this one can be broken down into two cases:
1) What should the function do on an empty list?
2) If I know what the function does on a list of length n, can I use that to figure out what the function should do on a list of length n + 1.
Once you know those two things, you have a definition that will work on any list (at least one of finite length - such a procedure will of course never end for one of infinite length; that doesn't matter here as it doesn't make much sense to talk about permutations from an infinite list). [If you have any sort of mathematical background, you will recognise this as a simple statement of the law of mathematical induction.]
For the perms function, it is clear that there is only one way to permute the 0 elements of the empty list: another empty list. This gives [[]] for the base case, as in the first line of the example solution.
For the recursive/inductive step, let's say we have a list xs of length n (where n > 0), and suppose (as we are allowed to) that we already know how to compute all permutations of any list of length n - 1.
Each permutation must start with a particular element of the xs - let's call this element i, and think about how to get all the permutations of xs whose first element is i. It should be clear that these correspond precisely with all permutations of the list delete i xs (that is, xs with one i removed) - given a permutation j of the latter, the list i : j is a permutation of xs which begins with i, and conversely all such permutations of xs can be obtained in that way.
Note that this is exactly the list [ i:j | j <- perms $ delete i xs ]
(And note in passing that, since we've assumed i is in xs, delete i xs indeed has length n - 1, so by the inductive hypothesis we know how to compute this.)
i of course was chosen completely arbitrarily there - and all elements of xs will need to be accounted for as the first element of some permutations. So we simply put together all of the above, for all elements i in xs - which is exactly what the expression in the recursive step is:
[ i:j | i <- xs, j <- perms $ delete i xs ]
You might need to read some of the above slowly, a few times, before it makes sense - but it is fundamentally very elementary logic (and like most elementary logic, has a nasty habit of often looking more complicated than it actually is).
One by one take a single element i from xs
Delete i from xs and prepend i to j (every list element of the perms of xs less i) up until all is are depleted.

Why the `foldr`, `foldr1`, `scanr` and `scanr1` functions haven't a _problem with productivity when they are applied to big lists?

I read the old Russian translate of the Learn You a Haskell for Great Good! book. I see that the current English version (online) is newer, therefore I look it time of time also.
The quote:
When you put together two lists (even if you append a singleton list
to a list, for instance: [1,2,3] ++ [4]), internally, Haskell has to
walk through the whole list on the left side of ++. That's not a
problem when dealing with lists that aren't too big. But putting
something at the end of a list that's fifty million entries long is
going to take a while. However, putting something at the beginning of
a list using the : operator (also called the cons operator) is
instantaneous.
I assumed that Haskell has to walk through the whole list to get the last item of the list for the foldr, foldr1, scanr and scanr1 functions. Also I assumed that Haskell will do the same for getting a previous element (and so on for each item).
But I see I was mistaken:
UPD
I try this code and I see the similar time of processing for both cases:
data' = [1 .. 10000000]
sum'r = foldr1 (\x acc -> x + acc ) data'
sum'l = foldl1 (\acc x -> x + acc ) data'
Is each list of Haskell bidirectional? I assume that for getting last item of list Haskell at first are to iterate each item and to remember the necessary item (last item for example) for getting (later) the previous item of bidirectional list (for lazy computation). Am I right?
It's tricky since Haskell is lazy.
Evaluating head ([1..1000000]++[1..1000000]) will return immediately, with 1. The lists will never be fully created in memory: only the first element of the first list will be.
If you instead demand the full list [1..1000000]++[1..1000000] then ++ will indeed have to create a two-million long list.
foldr may or may not evaluate the full list. It depends on whether the function we use is lazy. For example, here's map f xs written using foldr:
foldr (\y ys -> f y : ys) [] xs
This is efficient as map f xs is: lists cells are produced on demand, in a streaming fashion. If we need only the first ten elements of the resulting list, then we indeed create only the first ten cells -- foldr will not be applied to the rest of the list. If we need the full resulting list, then foldr will be run over the full list.
Also note that xs++ys can be defined similarly in terms of foldr:
foldr (:) ys xs
and has similar performance properties.
By comparison, foldl instead always runs over the whole list.
In the example you mention we have longList ++ [something], appending to the end of the list. This only costs constant time if all we demand is the first element of the resulting list. But if we really need the last element we added, then appending will need to run over the whole list. This is why appending at the end is considered O(n) instead of O(1).
In the last update, the question speaks about computing the sum with foldr vs foldl, using the (+) operator. In such case, since (+) is strict (it needs both arguments to compute result) then both folds witll need to scan the whole list. The performance in such cases can be comparable. Indeed, they would compute, respectively
1 + (2 + (3 + (4 + ..... -- foldr
(...(((1 + 2) + 3) +4) + .... -- foldl
By comparison foldl' would be more memory efficient, since it starts reducing the above sum before building the above giant expression. That is, it would compute 1+2 first (3), then 3+3 (6), then 6 + 4 (10),... keeping in memory only the last result (a single integer) while the list is being scanned.
To the OP: the topic of laziness is not easy to grasp the first time. It is quite vast -- you just met a ton of different examples which have subtle but significant performance differences. It's hard to explain everything succinctly -- it's just too broad. I'd recommend to focus on small examples and start digesting those first.

Infinite list of powers using subset of Haskell

I need to make a function "powers" that takes a number n and returns the infinite list of that number to the power of every number e.g.
powers 2 = 2,4,8,16,32......
I need to do this using very specific subset of the language where my only available built in functions are: div, mod, even, odd, head, tail, not, null, length, reverse, elem, map, filter, foldr, sum, product, take, drop, takewhile, dropWhile, zipWith and from.
the subset also has no ^ operator.
there are some further important constraints:
the code must not exceed 1 line of more than 80 characters
no "helper functions" allowed, i.e i cannot write another function to use within this definition.
So far my thinking is along these lines:
powers = \n -> map (\x -> "some function to get n to the power of x") (from 1)
but i cant figure out how to get the function to do this without a helper function.
for example if i was to use a function inflist that returned an infinite list of the number x then i could just do the following.
powers = \n -> map (\x -> product(take x (inflist n))) (from 1)
but i cant do this or anything like it because i couldn't use that function.
Sorry if the notation is a different to normal haskell, its a very strict core haskell subset that uses this notation.
This is a recursion question.
powers n = n : map (* n) (powers n)
(Are you allowed to use :?)
This was fun and funner when the insight came.
Generate successively longer repetitions of 2 in lists with
[ [ 2 | y <- [1..x]] | x <- [1..]]
Then take the product of each list.
map product [ [ 2 | y <- [1..x]] | x <- [1..]]
Be sure to use take x before an invocation
I struggled with a mod and multiple mod functions to limit lists.
If iterate were allowed.
take 24 $ iterate (2*) 2
would generate the list.
Edit 4/4/2018
An infinite recursive function, may be what you are looking for to fill out your function. It might be:
pow l = l ++ pow [(last l * 2)]
To produce a list it is absolutely necessary to assemble a list and it is necessary to use the last element of the list to calculate the next in sequence. This must also be run with take. Also the command following starts the list with 1. It can be started with any number such as 64 or 63. I tried passing the last value as a parameter but then the function would not generate a list. There is a choice, use ':' instead of '++' but it will produce each element in a list. To produce a list of values instead of a list of lists used 'concat $ ' before 'take' to clean it up.
take 10 $ pow [1]

Haskell: Minimum sum of list

So, I'm new here, and I would like to ask 2 questions about some code:
Duplicate each element in list by n times. For example, duplicate [1,2,3] should give [1,2,2,3,3,3]
duplicate1 xs = x*x ++ duplicate1 xs
What is wrong in here?
Take positive numbers from list and find the minimum positive subtraction. For example, [-2,-1,0,1,3] should give 1 because (1-0) is the lowest difference above 0.
For your first part, there are a few issues: you forgot the pattern in the first argument, you are trying to square the first element rather than replicate it, and there is no second case to end your recursion (it will crash). To help, here is a type signature:
replicate :: Int -> a -> [a]
For your second part, if it has been covered in your course, you could try a list comprehension to get all differences of the numbers, and then you can apply the minimum function. If you don't know list comprehensions, you can do something similar with concatMap.
Don't forget that you can check functions on http://www.haskell.org/hoogle/ (Hoogle) or similar search engines.
Tell me if you need a more thorough answer.
To your first question:
Use pattern matching. You can write something like duplicate (x:xs). This will deconstruct the first cell of the parameter list. If the list is empty, the next pattern is tried:
duplicate (x:xs) = ... -- list is not empty
duplicate [] = ... -- list is empty
the function replicate n x creates a list, that contains n items x. For instance replicate 3 'a' yields `['a','a','a'].
Use recursion. To understand, how recursion works, it is important to understand the concept of recursion first ;)
1)
dupe :: [Int] -> [Int]
dupe l = concat [replicate i i | i<-l]
Theres a few problems with yours, one being that you are squaring each term, not creating a new list. In addition, your pattern matching is off and you would create am infinite recursion. Note how you recurse on the exact same list as was input. I think you mean something along the lines of duplicate1 (x:xs) = (replicate x x) ++ duplicate1 xs and that would be fine, so long as you write a proper base case as well.
2)
This is pretty straight forward from your problem description, but probably not too efficient. First filters out negatives, thewn checks out all subtractions with non-negative results. Answer is the minumum of these
p2 l = let l2 = filter (\x -> x >= 0) l
in minimum [i-j | i<-l2, j<-l2, i >= j]
Problem here is that it will allow a number to be checkeed against itself, whichwiull lend to answers of always zero. Any ideas? I'd like to leave it to you, commenter has a point abou t spoon-feeding.
1) You can use the fact that list is a monad:
dup = (=<<) (\x -> replicate x x)
Or in do-notation:
dup xs = do x <- xs; replicate x x; return x
2) For getting only the positive numbers from a list, you can use filter:
filter (>= 0) [1,-1,0,-5,3]
-- [1,0,3]
To get all possible "pairings" you can use either monads or applicative functors:
import Control.Applicative
(,) <$> [1,2,3] <*> [1,2,3]
[(1,1),(1,2),(1,3),(2,1),(2,2),(2,3),(3,1),(3,2),(3,3)]
Of course instead of creating pairs you can generate directly differences when replacing (,) by (-). Now you need to filter again, discarding all zero or negative differences. Then you only need to find the minimum of the list, but I think you can guess the name of that function.
Here, this should do the trick:
dup [] = []
dup (x:xs) = (replicate x x) ++ (dup xs)
We define dup recursively: for empty list it is just an empty list, for a non empty list, it is a list in which the first x elements are equal to x (the head of the initial list), and the rest is the list generated by recursively applying the dup function. It is easy to prove the correctness of this solution by induction (do it as an exercise).
Now, lets analyze your initial solution:
duplicate1 xs = x*x ++ duplicate1 xs
The first mistake: you did not define the list pattern properly. According to your definition, the function has just one argument - xs. To achieve the desired effect, you should use the correct pattern for matching the list's head and tail (x:xs, see my previous example). Read up on pattern matching.
But that's not all. Second mistake: x*x is actually x squared, not a list of two values. Which brings us to the third mistake: ++ expects both of its operands to be lists of values of the same type. While in your code, you're trying to apply ++ to two values of types Int and [Int].
As for the second task, the solution has already been given.
HTH

Learning Haskell maps, folds, loops and recursion

I've only just dipped my toe in the world of Haskell as part of my journey of programming enlightenment (moving on from, procedural to OOP to concurrent to now functional).
I've been trying an online Haskell Evaluator.
However I'm now stuck on a problem:
Create a simple function that gives the total sum of an array of numbers.
In a procedural language this for me is easy enough (using recursion) (c#) :
private int sum(ArrayList x, int i)
{
if (!(x.Count < i + 1)) {
int t = 0;
t = x.Item(i);
t = sum(x, i + 1) + t;
return t;
}
}
All very fine however my failed attempt at Haskell was thus:
let sum x = x+sum in map sum [1..10]
this resulted in the following error (from that above mentioned website):
Occurs check: cannot construct the infinite type: a = a -> t
Please bear in mind I've only used Haskell for the last 30 minutes!
I'm not looking simply for an answer but a more explanation of it.
I'm not looking simply for an answer but a more explanation of it.
On the left-hand side of the = you use sum as a function applied to x. The compiler doesn't know the type of x, so the compiler uses type variable a to stand for "the type of x." At thus point the compiler doesn't know the result type of the function sum either, so it picks another type variable, this type t, to stand for the result type. Now on the left-hand side the compiler thinks that the type of x is a -> t (function accepting a and returning t).
On the right-hand side of the = you add x and sum. In Haskell all kinds of numbers can be added, but you can add two numbers only if they have the same type. So here the compiler assumes that sum has the same type as x, namely type a.
But in Haskell an identifier has one type—maybe a whangdilly complicated type, but one type nevertheless. This includes sum, whose type should be the same on both sides of the ` sign, so the compiler tries to solve the equation
a = a -> t
There are no values for a and t that solve this equation. It simply can't be done. There is no a such that a is equal to a function that accepts itself as an argument. Thus ariseth the error message
cannot construct the infinite type: a = a -> t
Even with all the explanation, it's not such a great error message, is it?
Welcome to Haskell :-)
P.S. You might enjoy trying "Helium, for learning Haskell", which gives much nicer error messages for beginners.
'sum' takes a list of values and reduces it to a single value. You can either write it as an explicit loop (remember that Haskell has no loop keywords, but uses recursion). Note how the definition has two parts, based on the shape of the list:
mysum [] = 0
mysum (x:xs) = x + mysum xs
Or more efficiently, in a tail-recursive style:
mysum xs = go 0 xs
where
go n [] = n
go n (x:xs) = go (n+x) xs
However, Haskell has a rich library of control structures that operate on lazy lists. In this case, reduction of a list to a single value can be done with a reduce function: a fold.
So mysum can be written as:
mysum xs = foldr (+) 0 xs
For example:
Prelude> foldr (+) 0 [1..10]
55
Your mistake was to use a map, which transforms a list, one element at a time, rather than a fold.
I'd suggest you start with an introduction to Haskell, perhaps "Programming in Haskell", to get a feel for the core concepts of functional programming. Other good introductory materials are described in this question.
You need to read a good tutorial, there are a number of big misunderstandings.
First I'm going to assume you mean lists and not arrays. Arrays exist in Haskell, but they aren't something you'd encounter at the beginner level. (Not to mention you're using [1..10] which is a list of the numbers 1 to 10).
The function you want is actually built in, and called sum, so we'll have to call our something else, new_sum:
new_sum [] = 0
new_sum (h:t) = h + (sum t)
Let's look at the first part of this:
let sum x = x+sum
What would the type of sum be in this case? It takes a number and returns a function that takes a number which returns a function that takes a number etc. if you had written it
let sum x = + x
you would have a function that takes a number and returns the function +x.
and
let sum = +
would return a function that takes two integers and adds them.
so now let's look at the second part.
in map sum [1..10]
map takes a function of one argument and applies it to every element of the list. There is no room to wedge an accumulator in there, so let's look at other list functions in particular foldl, foldr. both of these take a function of two arguments a list and a beginning value. The difference between foldl and foldr is on the side in which they start. l being left so 1 + 2 + 3 etc and r being right 10 + 9 + 8 etc.
let sum = (+) in foldl sum 0 [1..10]

Resources