I'm learning Haskell, and I was playing around in ghci when I came across something very puzzling.
First, create a simple add function:
Prelude> let add x y = x + y
Note that it works with ints and floats:
Prelude> add 3 4
7
Prelude> add 2.5 1.3
3.8
Now create an apply function. It's identical to $
(but not infix). It works like a no-op on add:
Prelude> let apply f x = f x
Prelude> apply add 3 4
7
Prelude> apply add 2.5 1.3
3.8
Ok, now make add'
which is the same as add'
but using apply
:
Prelude> let add' = apply add
Prelude> add' 3 4
7
Prelude> add' 2.5 1.3
<interactive>:1:9:
No instance for (Fractional Integer)
arising from the literal `1.3' at <interactive>:1:9-11
Possible fix: add an instance declaration for (Fractional Integer)
In the second argument of `add'', namely `1.3'
In the expression: add' 2.5 1.3
In the definition of `it': it = add' 2.5 1.3
Wat.
Here are the types:
Prelude> :t add
add :: (Num a) => a -> a -> a
Prelude> :t apply add
apply add :: (Num t) => t -> t -> t
Prelude> :t add'
add' :: Integer -> Integer -> Integer
Prelude>
Why does add'
have a different type than apply add
?
Is this a ghci oddity, or is this true in Haskell in general? (And how can I tell the difference?)
Quits GHCi. You can also quit by typing control-D at the prompt. Attempts to reload the current target set (see :load ) if any of the modules in the set, or any dependent module, has changed.
Simply type a let followed by a newline: let ⏎. Then fac 0 = 1 ⏎. Then fac n = n * fac (n-1) ⏎ ⏎ and you're done!
Open a command window and navigate to the directory where you want to keep your Haskell source files. Run Haskell by typing ghci or ghci MyFile. hs. (The "i" in "GHCi" stands for "interactive", as opposed to compiling and producing an executable file.)
Introduction. GHCi is GHC's interactive environment, in which Haskell expressions can be interactively evaluated and programs can be interpreted.
It's the Monomorphism restriction. When you define a value with a simple pattern binding (just the name, without any function arguments) and without a type signature, it gets a monomorphic type. Any type variables are tried to be disambiguated according to the defaulting rules, if that doesn't succeed you get a type error.
In this case, the Num
constrained type variable gets defaulted to Integer
.
You can turn off the monomorphism restriction with
ghci> :set -XNoMonomorphismRestriction
or with the -XnoMonomorphismRestriction
flag on the command line.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With