-4

How do I write a function that returns everything to Integer?

i.e

f True = 1
f False =0
f 1 = 1
f 2.30 = 2

  • possible duplicate of [Getting started with Haskell](http://stackoverflow.com/questions/1012573/getting-started-with-haskell) – David says Reinstate Monica Feb 25 '15 at 15:17
  • There exists the function `toInteger` that can convert any `Integral a => a` value to an `Integer`, but there is no way to convert any possible type to an `Integer`. You could write your own `ToInteger` typeclass, then add implementations for `Int`, `Bool`, `Float`, `Double`, etc, but no such thing exists already in Haskell. – bheklilr Feb 25 '15 at 16:13
  • 3
    What should `f my_function` return? What about `f [1,2,3]`? What does `f (print 5)` return? – MathematicalOrchid Feb 25 '15 at 16:14
  • @David, Getting started is a good place to review, but this question is not a duplicate of that by any stretch of the imagination. – Joseph Poirier Dec 05 '22 at 04:28

2 Answers2

14

The only functions of type a -> Integer will be constant functions. This is a free theorem guaranteed by the parametricity of the type (modulo some fudging because of some unsound corners of Haskell).

Here's an example of such a function:

f :: a -> Integer
f _ = 1
kini
  • 1,781
  • 13
  • 23
2

There's no way to do this in general, and it's not at all advisable, but the cases you mention, and some others, can be obtained using an ugly hack:

f :: Enum n => n -> Integer
f x = toInteger (fromEnum x)

As a general rule, it's best to simply pretend that the Enum class does not exist, because it is extremely badly designed and some of its instances are badly behaved.

dfeuer
  • 48,079
  • 5
  • 63
  • 167
  • Note that this will even break for `Integer` itself if the numbers are larger than what fits in an `Int`. – Ørjan Johansen Feb 26 '15 at 04:22
  • @ØrjanJohansen, what part of inadvisable ugly hack didn't you understand :-? You can "fix" that with a rewrite rule, probably, or some horrifying `OverlappingInstances` trick. – dfeuer Feb 26 '15 at 04:32
  • I understood perfectly, I just thought it needed a bit of evidence. Incidentally I recall someone recently complaining about `realToFrac :: Double -> Double`, which *does* have a rewrite rule which changes semantics depending on your optimization level. – Ørjan Johansen Feb 26 '15 at 04:50
  • @ØrjanJohansen, I tend to see all such functions and their rewrite rules (including even the ubiquitous `fromIntegral`) as shady. – dfeuer Feb 26 '15 at 05:22