Fireapprentice
Fireapprentice

Reputation: 117

Haskell - an infinite List which is divisible by every number of a given List

I am still a beginner in Haskell and currently I am trying to create a function in which i generate an infinite list from which I (if I use take 10 for example) take the first ten number, which are divisible by another list, which is given.

Here is my idea:

myCode :: [Int] -> [Int]
myCode (a:as) = [ x | x <- [0..] , x `mod` a == 0 , x `mod` myCode as ==0]

As you may have notices is that I am trying to solve it through recursion, however I always get the error "Couldn't match expected type ‘Bool’ with actual type ‘[Int]’ " I am kinda at a loss, because I wouldn't know how else to solve this particular problem.

Upvotes: 2

Views: 1359

Answers (1)

willeM_ Van Onsem
willeM_ Van Onsem

Reputation: 477170

No need to use recursion here: simply use all (or any) as condition:

alldiv :: [Int] -> Int -> Bool
alldiv l b = all (\n -> b `mod` n == 0) l

myCode :: [Int] -> [Int]
myCode as = [ x | x <- [0..] , alldiv as x]

You can rewrite alldiv to:

alldiv :: [Int] -> Int -> Bool
alldiv l b = all ((==) 0 . mod b) l

or even attach it locally to myCode:

myCode :: [Int] -> [Int]
myCode as = [ x | x <- [0..] , alldiv x]
    where alldiv b = all ((==) 0 . mod b) as

Finally you do not need list comprehension, you can simply use filter:

myCode :: [Int] -> [Int]
myCode as = filter alldiv [0..]
    where alldiv b = all ((==) 0 . mod b) as

EDIT

Since it is sufficient that it one element in the list is a divider, you only need to replace all with any.

Upvotes: 3

Related Questions