Haskell sqrt - converting a list of Integer to Float

1.6k views Asked by At

I need some help with my program. It's supposed to sqrt all element of a Integer list and give back a list of Float, in 3 variants: 1) recursive, 2) list comprehensions, 3) higher-order functions. I've wrote first one, which works fine:

-- recursive:

sqrtL1 :: [Integer] -> [Float]
sqrtL1 [] = []
sqrtL1 (n:ns)  = (sqrt x) : sqrtL1(ns)
    where x = fromIntegral n :: Float

-- Listenkomprehension:

sqrtL2 :: [Integer] -> [Float]
sqrtL2 (n:ns) = [sqrt x | x <- ns]
    where x = fromIntegral n :: Float  --(it doesn't work tho)

-- Higher-order:

sqrtL3 :: [Integer] -> [Float]
sqrtL3 ns = map sqrt ns

but I'm getting troubles with converting in the next two cases. Could someone help me?

1

There are 1 answers

1
asm On BEST ANSWER

The problem with sqrtL2 is x is not in scope outside the list comprehension. You need to do the fromIntegral inside the list comprehension like this:

sqrtL2 ns = [sqrt (fromIntegral x) | x <- ns]

sqrtL3 is fine except you don't have a fromIntegral anywhere and sqrt is Floating a => a -> a so it doesn't work with Integer. So you need this instead:

map (sqrt . fromIntegral) ns