File: part24.lhs

package info (click to toggle)
haskell98-tutorial 200006-3
  • links: PTS
  • area: main
  • in suites: sarge
  • size: 624 kB
  • ctags: 11
  • sloc: haskell: 2,125; makefile: 80; sh: 13
file content (57 lines) | stat: -rw-r--r-- 1,749 bytes parent folder | download | duplicates (6)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
Gentle Introduction to Haskell 98, Online Supplement 
Part 24
Covers Sections 12, 12.1, 12.2, 12.3

Section: 12  Typing Pitfalls

Section: 12.1  Let-Bound Polymorphism

> module Part24() where

> -- f g = (g 'a',g [])    -- This won't typecheck.

Section: 12.2  Overloaded Numerals

Overloaded numerics were covered previously - here is one more example.
sum is a prelude function which sums the elements of a list.

> average :: (Fractional a) => [a] -> a
> average xs   = sum xs / fromIntegral (length xs)

> e1 :: Float   -- Note that e1 would default to Double instead of Integer - 
>               -- this is due to the Fractional context.
> e1 = average [1,2,3]

Section: 12.3  The Monomorphism Restriction

The monomorphism restriction is usually encountered when functions
are defined without parameters.  If you remove the signature for sum'
the monomorphism restriction will apply.  Hugs (at present) incorrectly
defaults the type of sum' to Integer -> Integer without the type
signature.  If either of sumInt or sumFloat are present, these would
determine the overloading.  If both are present and sum' has no signature
there is an error. 

> sum' :: (Num a) => [a] -> a
> sum' = foldl (+) 0         -- foldl reduces a list with a binary function
>                            -- 0 is the initial value.

> sumInt :: Int
> sumInt = sum' [1,2,3]

> sumFloat :: Float
> sumFloat = sum' [1,2,3]

If you use overloaded constants you also may encounter monomorphism:

> x :: Num a => a
> x = 1    -- The type of x is Num a => a
> y :: Int
> y = x            -- Uses x as an Int
> z :: Integer
> z = x          -- Uses x as an Integer.  A monomorphism will occur of the
>                -- signature for x is removed.

Continued in part25.lhs