Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Haskell converting Float to Int

I'm still new and trying to create a list for use in a function and want to keep it as small as possible which happens to be logBase x y. but I'm having trouble getting logBase into something I can use in this list.

[1 .. (logBase x y)]

Any suggestions?

like image 305
SixOThree Avatar asked Sep 09 '09 01:09

SixOThree


People also ask

How do you convert float to Int Haskell?

In Haskell, we can convert Float to Int using the function round .

What does fromIntegral do 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 is the difference between Int and integer in Haskell?

What's the difference between Integer and Int ? Integer can represent arbitrarily large integers, up to using all of the storage on your machine. Int can only represent integers in a finite range. The language standard only guarantees a range of -229 to (229 - 1).

How do you divide in Haskell?

The (/) function requires arguments whose type is in the class Fractional, and performs standard division. The div function requires arguments whose type is in the class Integral, and performs integer division. More precisely, div and mod round toward negative infinity.


1 Answers

You don't post what type error you get, but I imagine it is something like this:

Prelude> let x = 2
Prelude> let y = 7
Prelude> [1 .. (logBase x y)] 

<interactive>:1:7:
    No instance for (Floating Integer)
      arising from a use of `logBase' at <interactive>:1:7-17
    Possible fix: add an instance declaration for (Floating Integer)
    In the expression: (logBase x y)
    In the expression: [1 .. (logBase x y)]
    In the definition of `it': it = [1 .. (logBase x y)]

The problem is that:

Prelude> :t logBase
logBase :: (Floating a) => a -> a -> a

returns a type in the Floating class, while other variables in your program (1, 'x', 'y') are of integral type.

I presume you want a sequence of Integers?

Prelude> :set -XNoMonomorphismRestriction
Prelude> let x = 2
Prelude> let y = 42
Prelude> [1 .. truncate (logBase x y)] 
[1,2,3,4,5]

Use truncate, celing or floor.

like image 151
Don Stewart Avatar answered Oct 05 '22 13:10

Don Stewart