[Haskell-beginners] can somebody explain the type of this expression?
Mike Meyer
mwm at mired.org
Mon Oct 27 20:54:07 UTC 2014
On Mon, Oct 27, 2014 at 3:47 PM, Ovidiu Deac <ovidiudeac at gmail.com> wrote:
> Prelude> let f x = x * 2
> Prelude> :t f
> f :: Num a => a -> a
>
> The typeclass Num is defined like this:
>
> class Num a where
> (+), (-), (*) :: a -> a -> a
> ...
>
> ...which means that the operator (*) expects two parameters of type a and
> returns a value of type a.
>
> Since the definition of expr looks like this:
> Prelude> let f x = x * 2
>
> ...and 2 is an Int, I would expect that the type inferred for (*) is (Int
> -> Int -> Int) and thus f should be (Int -> Int)
>
> Can somebody explain this?
>
> Thanks!
>
Not sure of the terminology, but 2 can be coerced to any different type of
Num, so that it can be used in non-Int expressions:
2 / 3
0.6666666666666666
Prelude> :t 2 / 3
2 / 3 :: Fractional a => a
Prelude> :t 2
2 :: Num a => a
Note that Fractional is also a type class, not a type like Int, so Floating
types do the same thing. For that mater, if you enabled OverloadedStrings,
you can get that behavior out of strings:
Prelude> :t "abc"
"abc" :: [Char]
Prelude> :set -XOverloadedStrings
Prelude> :t "abc"
"abc" :: Data.String.IsString a => a
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://www.haskell.org/pipermail/beginners/attachments/20141027/e6d02205/attachment.html>
More information about the Beginners
mailing list