Gloria95
Gloria95

Reputation: 139

How to use list comprehension in Haskell?

I am trying to teach myself Haskell and I am doing random exercises. I was supposed to write a code that will do this 6 = [1*1 + 3*3 + 5*5]= 35 So I had to filter out all odd numbers and then calculate the sum if I multiply every single one with itself.

 sumquad n = (potenzsum(filter odd (ones n)))
     where
     potenzsum [x] = x*x
     potenzsum [x,y] = x*x + y*y
     potenzsum (x:xs) = x + potenzsum xs

ones 0 = []
ones x = [ 1 .. x] 

This code works ;) Now I am supposed to do the same thing but with list comprehension (I am allowed to use this list [1...n]

I could only think of this... Could someone help me?

power1 xs = [x*x | x <- xs]

Upvotes: 3

Views: 4899

Answers (1)

Igor Drozdov
Igor Drozdov

Reputation: 15045

Actually, you did half the job by [x * x | x <- xs], just replace xs by odd numbers from the previous example:

[x * x | x <- filter odd (ones 6))]

And you'll receive a list of squares: [1, 9, 25], which can be summed by function sum:

f n = sum [x * x | x <- filter odd (ones n))]

it evaluates to 35

One more note regarding list comprehension: the iterated elements can be filtered out by specifying conditions, which are called guards. Thus, the code above can be refactored into:

f n = sum [x * x | x <- [1..n], odd x]

Upvotes: 4

Related Questions