Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Haskell - how to cast types?

I am trying to do following:

10 ** length xs * x

but I get:

No instance for (Floating Int) arising from a use of `**'

like image 322
MMM Avatar asked May 22 '10 21:05

MMM


People also ask

Can you type cast in Haskell?

Haskell takes a very different approach. It starts by performing type analysis with a type checker to understand your program at compile time. The type checker strictly prohibits type casting and does not allow type errors to be ignored.

What does fromIntegral do in Haskell?

The workhorse for converting from integral types is fromIntegral , which will convert from any Integral type into any Num eric type (which includes Int , Integer , Rational , and Double ): fromIntegral :: (Num b, Integral a) => a -> b.

What are types in Haskell?

In Haskell, every statement is considered as a mathematical expression and the category of this expression is called as a Type. You can say that "Type" is the data type of the expression used at compile time.


2 Answers

You can use ^ to raise to an integral power. There's no need to convert to float here.

like image 138
sepp2k Avatar answered Sep 25 '22 20:09

sepp2k


Besides @sepp2k's answer, if you somehow really need to convert from an integer to some other types of Num, use fromIntegral.

-- # fromIntegral :: (Integral a, Num b) => a -> b

10 ** fromIntegral (length xs) * x
like image 39
kennytm Avatar answered Sep 24 '22 20:09

kennytm