user12240282
user12240282

Reputation:

Creating list with multiple conditions in haskell

Define the sequence (bn)n=1,2,… such that bn=3 when n is divisible by 3, and bn=4(n+1)^2 in other cases. Define a function that for an argument n creates the list of n initial numbers of the sequence (bn)n=1,2,… .

so far I have two lists with condition 1 and condition 2:
divisible3 n = [x | x <- [1..n], x `mod` 3 == 0]
notdivisible3 n = [x*x*4+8*x+4 | x <- [1..n], x `mod` 3 /= 0]
I want it to be one list like:
list n = [x | x <- [1..n], condition1, condition 2]

Upvotes: 1

Views: 452

Answers (1)

willeM_ Van Onsem
willeM_ Van Onsem

Reputation: 477170

You should write an if ... then ... else ... in the "yield" part of the list comprehension, not a filter. So something like:

list n = [ if n `mod` 3 == 0 then … else … | x <- [1..n]]

where I leave the parts as an exercise.

Upvotes: 1

Related Questions