Haskell squaring list elements and then adding them together - list

I have written divisible_by2 to square all elements in a list that are even and are less than twenty. My second function sum2 sums all the of the elements of divisible_by2. I need help combining these function so that when running divisible_by2 both functions are compiled.
divisible_by2 = [ x * x| x <- [2,4..18]]
sum2 = foldr (+) 1 divisible_by2
When running separately both functions give the correct output
*Main> :r
Ok, 1 module loaded.
*Main> divisible_by2
[4,16,36,64,100,144,196,256,324]
*Main> sum2
1141
*Main>

I guess you just want:
foo = (divisible_by2, sum2)
Also, that 1 in your foldr (+) 1 looks weird. You probably want a 0 there instead, or perhaps want to just replace the whole foldr expression with a call to sum.

Related

Does indexing a mapped/filtered infinite list apply the map/filter function to all the elements before the index?

If I define an infinite list and call map over it with a function, I can take some number of elements from the beginning and Haskell will generate and apply the function only to these elements due to lazy evaluation
-- This will generate and process 10 elements
doubledNumbers = map (*2) [0..]
take 10 doubledNumbers
If I index this infinite mapping instead
doubledNumbers !! 9
will Haskell generate the list up to that point, apply the mapping function to all elements and give the element at index 9 back; or will it generate the list, apply the mapping function to the element at index 9, and give that back. In other words, which of the following (if any) would happen when I call doubledNumbers !! 9
The list [0,1,2,3,4,5,6,7,8,9] is generated, then the list [0,2,4,6,8,10,12,14,16,18], then 18 is taken from that list
The list [0,1,2,3,4,5,6,7,8,9] is generated, than 9 is taken from that list and given to (*2) , than (*2) returns 18
The second interpretation is the correct one (well, morally at least: see below for a better explanation):
The list [0,1,2,3,4,5,6,7,8,9] is generated, than 9 is taken from that list and given to (*2) , than (*2) returns 18
You can observe that the function ((*2) in your case) is not applied to other elements with the following experiment. First, define a function that will crash on every number except 9:
f 9 = 100 ; f _ = error "urk!"
Then try your code in GHCi, adapted to the new function
> doubledNumbers = map f [0..]
> doubledNumbers !! 9
100
If GHCi applied f to any other number you would observe the crash. This is a way to distinguish, through an experiment, lazy evaluation from eager evaluation.
More pedantically, entering in GHCi the code
> doubledNumbers = map (*2) [0..]
> doubledNumbers !! 9
will first generate a list similar to
(*2) 0 : (*2) 1 : .... : (*2) 9 : map (*2) [10..]
where the expressions are not yet evaluated. After that, GHCi will extract the 9th, causing it to be evaluated and printed.
Neither interpretation is correct. In fact, the list that's generated can be thought to look something like this:
[_,_,_,_,_,_,_,_,_,_...
In other words, the spine, or shape, of the list is forced up through the 9th element (and no further), but the actual values in the list aren't. Then, when you ask for the 9th element of the mapped list, GHC calls the function on that element without evaluating it unless necessary. You can observe this with the following experiment:
errorList = repeat (error "fail!")
trueList = map (const True) errorList
val = trueList !! 9
If the list were actually produced in the first place, then val would fail with fail! as soon as we try to print it. However, val properly is True.
Using the tracing facility:
It is often possible to answer this type of question using a little but handy tracing facility included in the Haskell runtime library.
So there is a trace function, such that evaluating the expression trace debugMsg expr will return the value of expr and, as a side effect, print the value of debugMsg to the standard error channel.
Yes, side effects are normally not available in Haskell, but the trace function enjoys a special privilege :-)
So you can replace your (*2) function with the equivalent one:
import qualified Debug.Trace as DT
doubler :: Int -> Int
doubler x = let debugMsg = "Doubling " ++ (show x) ++ " ... "
in DT.trace debugMsg (2*x)
And then you can test the various hypothesis under the ghci interpreter:
$ ghci
GHCi, version 8.8.4: https://www.haskell.org/ghc/ :? for help
λ>
λ> :load q65861408.hs
[1 of 1] Compiling Main ( q65861408.hs, interpreted )
Ok, one module loaded.
λ>
λ> :type doubler
doubler :: Int -> Int
λ>
λ> doubler 5
Doubling 5 ...
10
λ>
λ> doubledNumbers = map doubler [0..]
λ>
λ> doubledNumbers !! 9
Doubling 9 ...
18
λ>
And so it appears that, as mentioned in the other answers, the doubling function is only invoked for the input value 9.
This is because of the language laziness: the user did not ask to see the other doubled values, hence there is no need to compute them in the first place.

Standard ML recursive function error

So i just got in ML programming and I found this excercise in a book. The excercise says to build a recursive function that takes an integer and a list. If L=[a1,a2,a3] then the desired result is [ai+1,ai+2,...,an,a1,a2,...,ai]. So I wrote a function and after a lot of hours I narrowed the errors down to one which I can't understand. Here is my function:
fun cycle L i =
if i = 0 then L
else (cycle tl(L) (i-1)) # [hd(L)];
I will upload an image with the error that i get so someone can explain to me what the interpreter is trying to say to me.
The numbers next to the "a" just show the order of these elements in the list.So for L=[1,2,3,4,5] and for i = 2, the desire result is the List L=[3,4,5,1,2]. I don't think that the type of list is essential in this problem. Hope this further explanation helped
It's a syntactic problem with the recursive call cycle tl(L) (i-1).
In SML, the syntax for function application is juxtaposition, not parentheses. In your case tl(L) indeed calls the function tl with argument L, but that's equivalent to just tl L. The parentheses are redundant and, as such, ignored.
Now, if you replace the minimal version within your original call, you'll get this: cycle tl L (i-1). It's calling cycle with three arguments, instead of just two.
The correct way of writing it would be: cycle (tl L) (i-1).
Ionuț already gave a sufficient answer to the syntax problem; here are some further suggestions:
Use pattern matching rather than hd and tl.
Consider the base cases; what are the simplest sub-problems you can think of? E.g. cycling the empty list will always give the empty list regardless of n, and cycling L 0 times will always give L back. Having both base cases as patterns helps.
Consider the recursive case; the top element (assuming it exists) is cycled and i is reduced by one, until eventually i is 0 or L is empty. Because the second base case catches the empty list, we can freely assume that L is non-empty here, in which case it will match the pattern x::xs.
fun cycle 0 xs = xs
| cycle i [] = []
| cycle i (x::xs) = cycle (i-1) (xs # [x])
Depending on whether 0 <= i and i <= length xs are preconditions for the function or not, you may want to handle these once before activating the main recursion, e.g. by wrapping the function above:
fun cycle i ys =
let fun fun cycle' 0 xs = xs
| cycle' i [] = []
| cycle' i (x::xs) = cycle' (i-1) (xs # [x])
in
if 0 <= i andalso i <= length xs
then cycle' i ys
else raise Domain
end
The main operation, namely xs # [x] is terribly inefficient, since its running time is proportional to the length of xs and is activated n times. So the running time of cycle becomes O(n • |L|) when something like O(min(n,|L|)) should be achievable.
You could probably make a much faster version if you store the cycled elements in a separate list, without using #, and combine the remaining elements with this list after the elements have been cycled. Depending on what you felt about 0 <= i and i <= length xs, you may run into problems with the following test case:
val cycle_test_1 = (cycle 5 [1,2,3,4] = [2,3,4,1])

How do you make a list in Haskell using two numbers?

Here is my problem: Declare type and define a function that takes two numbers m and n as input and returns a list containing the doubled values of all odd integers between m and n. For instance, fun 2 11 would return [6, 10, 14, 18, 22].
I don't know how I can take the two number 2 and 11 and make it into a list [2..11]. Does anyone know how to do this?
Use sequence generation (range syntax):
Prelude> [2 .. 11]
[2,3,4,5,6,7,8,9,10,11]
Works for symbolic values, too:
Prelude> let [m,n] = [2,11]
Prelude> [m .. n]
[2,3,4,5,6,7,8,9,10,11]
Didn't work with Haskell for almost two years, so correct me if I'm wrong and it doesn't work:
getDoubledOdd :: Int -> Int -> [Int]
getDoubledOdd m n = map (2*) $ filter odd [m..n]
A combination of list comprehension and range would be the most standard way to do it.
[ 2*x | x <- [2..11], odd x ]
The code basically says "let x loop from 2 to 11 (x <- [2..11]), and if x is odd (odd x), put 2*x into the list that will be returned".
Hope that explains.

Haskell: List Boundary

I have a list of doubles(myList), which I want to add to a new List (someList), but once the new list reaches a set size i.e. 25, I want to stop adding to it. I have tried implementing this function using sum but was unsuccessful. Example code below.
someList = [(a)| a <- myList, sum someList < 30]
The way #DanielFischer phrased the question is compatible with the Haskell way of thinking.
Do you want someList to be the longest prefix of myList that has a sum < 30?
Here's how I'd approach it: let's say our list is
>>> let list = [1..20]
we can find the "cumulative sums" using:
>>> let sums = tail . scanl (+) 0
>>> sums list
[1,3,6,10,15,21,28,36,45,55,66,78,91,105,120,136,153,171,190,210]
Now zip that with the original list to get pairs of elements with the sum up to that point
>>> zip list (sums list)
[(1,1),(2,3),(3,6),(4,10),(5,15),(6,21),(7,28),(8,36),
(9,45),(10,55),(11,66),(12,78),(13,91),(14,105),(15,120),
(16,136),(17,153),(18,171),(19,190),(20,210)]
Then we can takeWhile this list to get the prefix we want:
>>> takeWhile (\x -> snd x < 30) (zip list (sums list))
[(1,1),(2,3),(3,6),(4,10),(5,15),(6,21),(7,28)]
finally we can get rid of the cumulative sums that we used to perform this calculation:
>>> map fst (takeWhile (\x -> snd x < 30) (zip list (sums list)))
[1,2,3,4,5,6,7]
Note that because of laziness, this is as efficient as the recursive solutions -- only the sums up to the point where they fail the test need to be calculated. This can be seen because the solution works on infinite lists (because if we needed to calculate all the sums, we would never finish).
I'd probably abstract this and take the limit as a parameter:
>>> :{
... let initial lim list =
... map fst (takeWhile (\x -> snd x < lim) (zip list (sums list)))
... :}
This function has an obvious property it should satisfy, namely that the sum of a list should always be less than the limit (as long as the limit is greater than 0). So we can use QuickCheck to make sure we did it right:
>>> import Test.QuickCheck
>>> quickCheck (\lim list -> lim > 0 ==> sum (initial lim list) < lim)
+++ OK, passed 100 tests.
someList = makeList myList [] 0 where
makeList (x:xs) ys total = let newTot = total + x
in if newTot >= 25
then ys
else makeList xs (ys ++ [x]) newTot
This takes elements from myList as long as their sum is less than 25.
The logic takes place in makeList. It takes the first element of the input list and adds it to the running total, to see if it's greater than 25. If it is, we shouldn't add it to the output list, and we finish recursing. Otherwise, we put x on the end of the output list (ys) and keep going with the rest of the input list.
The behaviour you want is
ghci> appendWhileUnder 25 [1..5] [1..5]
[1,2,3,4,5,1,2,3]
because that sums to 21 and adding the 4 would bring it to 25.
OK, one way to go about this is by just appending them with ++ then taking the initial segment that's under 25.
appendWhileUnder n xs ys = takeWhileUnder n (xs++ys)
I don't want to keep summing intermediate lists, so I'll keep track with how much I'm allowed (n).
takeWhileUnder n [] = []
takeWhileUnder n (x:xs) | x < n = x:takeWhileUnder (n-x) xs
| otherwise = []
Here I allow x through if it doesn't take me beyond what's left of my allowance.
Possibly undesired side effect: it'll chop out bits of the original list if it sums to over 25. Workaround: use
appendWhileUnder' n xs ys = xs ++ takeWhileUnder (n - sum xs)
which keeps the entire xs whether it brings you over n or not.

Convert list of Integers into one Int (like concat) in haskell

Pretty much what the title says. I have a list of Integers like so: [1,2,3]. I want to change this in to the Integer 123. My first thought was concat but that doesn't work because it's of the wrong type, I've tried various things but usually I just end up returning the same list. Any help greatly appreciated.
Also I have found a way to print the right thing (putStr) except I want the type to be Integer and putStr doesn't do that.
You can use foldl to combine all the elements of a list:
fromDigits = foldl addDigit 0
where addDigit num d = 10*num + d
The addDigit function is called by foldl to add the digits, one after another, starting from the leftmost one.
*Main> fromDigits [1,2,3]
123
Edit:
foldl walks through the list from left to right, adding the elements to accumulate some value.
The second argument of foldl, 0 in this case, is the starting value of the process. In the first step, that starting value is combined with 1, the first element of the list, by calling addDigit 0 1. This results in 10*0+1 = 1. In the next step this 1 is combined with the second element of the list, by addDigit 1 2, giving 10*1+2 = 12. Then this is combined with the third element of the list, by addDigit 12 3, resulting in 10*12+3 = 123.
So pointlessly multiplying by zero is just the first step, in the following steps the multiplication is actually needed to add the new digits "to the end" of the number getting accumulated.
You could concat the string representations of the numbers, and then read them back, like so:
joiner :: [Integer] -> Integer
joiner = read . concatMap show
This worked pretty well for me.
read (concat (map show (x:xs))) :: Int
How function reads:
Step 1 - convert each int in the list to a string
(map show (x:xs))
Step 2 - combine each of those strings together
(concat (step 1))
Step 3 - read the string as the type of int
read (step 2) :: Int
Use read and also intToDigit:
joinInt :: [Int] -> Int
joinInt l = read $ map intToDigit l
Has the advantage (or disadvantage) of puking on multi-digit numbers.
Another idea would be to say: the last digit counts for 1, the next-to last counts for 10, the digit before that counts for 100, etcetera. So to convert a list of digits to a number, you need to reverse it (in order to start at the back), multiply the digits together with the corresponding powers of ten, and add the result together.
To reverse a list, use reverse, to get the powers of ten you can use iterate (*10) 1 (try it in GHCi or Hugs!), to multiply corresponding digits of two lists use zipWith (*) and to add everything together, use sum - it really helps to know a few library functions! Putting the bits together, you get
fromDigits xs = sum (zipWith (*) (reverse xs) (iterate (*10) 1))
Example of evaluation:
fromDigits [1,2,3,4]
==> sum (zipWith (*) (reverse [1,2,3,4]) [1,10,100,1000, ....]
==> sum (zipWith (*) [4,3,2,1] [1,10,100,1000, ....])
==> sum [4 * 1, 3 * 10, 2 * 100, 1 * 1000]
==> 4 + 30 + 200 + 1000
==> 1234
However, this solution is slower than the ones with foldl, due to the call to reverse and since you're building up those powers of ten only to use them directly again. On the plus side, this way of building numbers is closer to the way people usually think (at least I do!), while the foldl-solutions in essence use Horner's rule.
join :: Integral a => [a] -> a
join [x] = x
join (x:xs) = (x * (10 ^ long)) + join(xs)
where long = length(x:xs)
We can define the function called join, that given a list of Integral numbers it can return another Integral number. We are using recursion to separate the head of the given list with the rest of the list and we use pattern matching to define an edge condition so that the recursion can end.
As for how to print the number, instead of
putStr n
just try
putStr (show n)
The reasoning is that putStr can only print strings. So you need to convert the number to a string before passing it in.
You may also want to try the print function from Prelude. This one can print anything that is "showable" (any instance of class Show), not only Strings. But be aware that print n corresponds (roughly) to putStrLn (show n), not putStr (show n).
I'm no expert in Haskell, but this is the easiest way I can think of for a solution to this problem that doesn't involve using any other external functions.
concatDigits :: [Int] -> Int
concatDigits [] = 0
concatDigits xs = concatReversed (reverseDigits xs) 1
reverseDigits :: [Int] -> [Int]
reverseDigits [] = []
reverseDigits (x:xs) = (reverseDigits xs) ++ [x]
concatReversed :: [Int] -> Int -> Int
concatReversed [] d = 0
concatReversed (x:xs) d = (x*d) + concatReversed xs (d*10)
As you can see, I've assumed you're trying to concat a list of digits. If by any chance this is not your case, I'm pretty sure this won't work. :(
In my solution, first of all I've defined a function called reverseDigits, which reverses the original list. For example [1,2,3] to [3,2,1]
After that, I use a concatReversed function which takes a list of digits and number d, which is the result of ten power the first digit on the list position. If the list is empty it returns 0, and if not, it returns the first digit on the list times d, plus the call to concatReversed passing the rest of the list and d times 10.
Hope the code speaks for itself, because I think my poor English explanation wasn't very helpful.
Edit
After a long time, I see my solution is very messy, as it requires reversing the list in order to be able to multiply each digit by 10 power the index of the digit in the list, from right to left. Now knowing tuples, I see that a much better approach is to have a function that receives both the accumulated converted part, and the remainder of the list, so in each invocation in multiplies the accumulated part by 10, and then adds the current digit.
concatDigits :: [Int] -> Int
concatDigits xs = aggregate (xs, 0)
where aggregate :: ([Int], Int) -> Int
aggregate ([], acc) = acc
aggregate (x:xs, acc) = aggregate (xs, (acc * 10 + x))