Trouble with Floating

Viewed 46

Apologies if this problem is really straight-forward, but I've been messing a bit with a random piece of code I made and I'm curious why the following won't compile:

test::Floating a => Int -> [a]
test x = map(\y -> (y * abs(cos(y)))) [0..x]

I'm trying to understand most typeclasses and I thought of using Floating since we're using cosine. The goal of the function is to make a list of 0 to x with the following function: \y -> (y * abs(cos(y)))

However the compiler complains about the type of x ("Couldn't match type 'a' with 'Int'"), saying it expects a type [a] but receives [Int]. Why is this? After all I'm feeding those integers to my anonymous function to get a list of Floats.

1 Answers

since x is an Int, that means [0..x] is a list of Ints, and therefore y is also an Int, since all functions like (*) :: Num a => a -> a -> a require the two operands and the result to be the same type, this will thus not work.

You can however make use of fromIntegral :: (Integral a, Num b) => a -> b to convert a number of the Integral type to any Num type:

test :: Floating a => Int -> [a]
test x = map(\y -> let yf = fromIntegral y in yf * abs (cos yf)) [0..x]
Related