I can build a data structure that is a member of the Traversable
typeclass (e.g. List
or Map
), by mapping (map
, mapM
) or folding (foldl
, foldM
) another traversable data structure.
However, I often encounter situations where I need to build a traversable data structure with a member of the Num
typeclass (e.g. Integer
).
My usual approach here is to build a list by using a recursive operation - for example:
foo :: Integer -> [Integer] -> [Integer]
foo n fs
| m < 2 = fs
| rem m 2 == 0 = foo (m - 1) (m:fs)
| otherwise = foo (m - 1) fs
where m = abs n
This function returns the absolute values of the integers that are divisible by two, and are between 2 and n (inclusive).
Using the above example, is there an idiomatic way to build a list from a non-traversable without using recursion?