Co się dzieje z typami w tej sesji ghci?
Uczę się Haskella i bawiłem się w Ghci, kiedy natknąłem się na coś bardzo zagadkowego.
Najpierw utwórz prostą funkcję dodawania:
Prelude> let add x y = x + y
Zauważ, że działa z ints i float:
Prelude> add 3 4
7
Prelude> add 2.5 1.3
3.8
Teraz utwórz funkcję stosowania. Jest identyczny z$
(ale nie infix). Działa to jak dodanie:
Prelude> let apply f x = f x
Prelude> apply add 3 4
7
Prelude> apply add 2.5 1.3
3.8
Ok, teraz zróbadd'
który jest taki sam jakadd'
ale używającapply
:
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.
Oto typy:
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>
Dlaczegoadd'
mieć inny typ niżapply add
?
Czy to dziwactwo, czy w ogóle jest to prawdą w Haskell? (A jak mogę to odróżnić?)