David Matuszek
David Matuszek

Reputation: 1263

Is it possible to write a Haskell function with type Int -> Float

I can write

double :: Int -> Float
double i = 2.0

but that isn't in any way a function of its argument. Casting is apparently forbidden, mixed-mode arithmetic isn't supported, so I can't do anything like

double :: Int -> Float
double i = 2.0 * i

I'm actually trying to figure out how to define

series :: (Int -> Float) -> Int -> [Float]

to return the infinite series [f(i), f(i+1), f(i+2),...] but I'm stuck at computing f(i).

If this is really impossible, what type must I use?

Thanks!

Upvotes: 2

Views: 134

Answers (2)

dfeuer
dfeuer

Reputation: 48611

Michael Snoyman's answer is the practical one, but let me show you what you could do if fromIntegral didn't exist. First, the super-slow version:

intToFloat :: Int -> Float
intToFloat x
  | x > 0 = - itf (- x)
  | otherwise = itf x

-- Convert a negative Int to a Float
itf 0 = 0
itf x = itf (x + 1) - 1

This is slow, and may also use a lot of memory. But we can fix it through the power of division! Unfortunately, I can't write it up right now.

Upvotes: 1

Michael Snoyman
Michael Snoyman

Reputation: 31315

I think you're looking for the fromIntegral function.

Upvotes: 9

Related Questions