Calculate Intenes roots of Integer in Haskell

0

I need a function that does the following

raizEnesima :: Integer -> Integer -> Integer

raizEnesima 8 3 == 2
raizEnesima 7 8 == 1
raizEnesima 4 2 == 2

I have tried to perform the function, in the following way, but it gives me an error, and I do not know the reason:

raizEnesima :: Integer -> Integer -> Integer
raizEnesima n x = (round . fromInteger) (n**(1/x))

I hope you can help me. Thank you.

    
asked by aprendiendo-a-programar 17.01.2018 в 19:55
source

1 answer

1

The operator (/) is the "Fractional" ( Fractional ), while (**) is the "Rational" ( Rational ) . Both type classes do not have instances for Integer .

Explained better: there are no Fractional Integer or Rational Integer , so you can not use Integers in the expression n**(1/n) without more.

In other languages there are automatic type conversions. But haskell, operations between numbers are "internal" or, put another way, an operation of two integers always results in another integer. Operations (/) and (**) applied to integers would produce erroneous results, which is why they are not defined for these numbers. It is necessary to convert them to another more suitable type.

The simplest thing is to let the compiler choose the most appropriate type from the whole number, for which the fromIntegral function is:

raizEnesima :: Integer -> Integer -> Integer
raizEnesima n x = round $ (fromIntegral n**(1/fromIntegral x))

You can use fromInteger instead of fromIntegral if you want, although this is more general.

    
answered by 18.01.2018 в 12:12