Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert List comprehension into recursive call

sieve [] = []
sieve (a:x) = a : sieve [y| y <- x, y `mod` a > 0]

I want to convert this code to recursive implementation or using higher order functions such as map and filter. I can't figure out how do I do this.

I have tried this way but it wont seem to work

sieve (a:x) = f x : map f xs where f = y `mod` a > 0
like image 510
denizen Avatar asked Jan 22 '26 11:01

denizen


1 Answers

Is this the kind of thing you want? The list comprehension is only being used to filter the list anyway, so we can convert to a form that manually applies a filter.

sieve []     = []
sieve (x:xs) = x : sieve (filter (\y -> y `mod` x > 0) xs)
like image 120
Chris Taylor Avatar answered Jan 25 '26 13:01

Chris Taylor



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!