generate sequence with squares, cubes and factorials of natural numbers

Tag: haskell Author: shoshosho9 Date: 2012-03-06

elements must be unique, how can I do it with Haskell

I tryed with iterate and tuples and it works but how can I check was this number in sequence or not (iterate thru all sequence is not optimal decision :).

I think you are approaching this the wrong way round! If you want to find out if a number is in the sequence you can either check it is a square, cube, or factorial, or you can generate all the numbers and check whether it is a member (which seems to be what you are proposing). I'd approach this by writing some predicates, isSquare, isCube and isFactorial.
I don't want to check if it is in the sequence, I want to get the sequence

Best Answer

Since each sequence will be in ascending order, you can write a merge function to merge ascending lists (or use the one from the ordlist package).

merge [] ys = ys
merge xs [] = xs
merge (x:xs) (y:ys) =
    case compare x y of
        LT -> x : merge xs (y:ys)
        EQ -> x : merge xs ys
        GT -> y : merge (x:xs) ys

Then, you can define the final sequence by merging the other ones together:

squares = map (^2) [1..]
cubes = map (^3) [1..]
factorials = scanl1 (*) [1..]

foo = squares `merge` cubes `merge` factorials
> take 20 foo

Other Answer1

squares = map (^2) [1..]
cubes = map (^3) [1..]
factorials = scanl1 (*) [1..]

merge (x:xs) (y:ys) | x == y = x : merge xs ys
                    | x < y = x : merge xs (y:ys)
                    | otherwise = y : merge (x:xs) ys  

take 20 $ factorials `merge` squares `merge` cubes