Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Converting Floating to Integer

Tags:

haskell

I am trying to define:

square :: Integer -> Integer 
square = round . (** 2)

and I am getting:

<interactive>:9:9: error:
    • No instance for (RealFrac Integer) arising from a use of ‘round’
    • In the first argument of ‘(.)’, namely ‘round’
      In the expression: round . (** 2)
      In an equation for ‘square’: square = round . (** 2)

<interactive>:9:18: error:
    • No instance for (Floating Integer)
        arising from an operator section
    • In the second argument of ‘(.)’, namely ‘(** 2)’
      In the expression: round . (** 2)
      In an equation for ‘square’: square = round . (** 2)

I am still new in this language and I seem to be unable to convert an instance of Floating to an Integer. Does anybody know how can I do so?

like image 909
Pedro Rolo Avatar asked Jul 04 '26 02:07

Pedro Rolo


1 Answers

Haskell has multiple exponent functions with different types:

  • (^) :: (Num a, Integral b) => a -> b -> a
  • (^^) :: (Fractional a, Integral b) => a -> b -> a
  • (**) :: Floating a => a -> a -> a

The one you are looking for is just (^). With it, you don't even need round:

square :: Integer -> Integer 
square = (^ 2)
like image 89
Alec Avatar answered Jul 06 '26 20:07

Alec