Tonλ's blog May the λ be with you

Programming in haskell - Ch3 - Types and classes

by @ardumont on

Types of values

What are the types of the following values?

  • [’a', 'b', 'c']
  • ('a', 'b', 'c')
  • [(False, 'O'), (True, '1')]
  • ([False, True ], ['0', '1'])
  • [tail , init, reverse ]
Values Types
['a', 'b', 'c'] [Char]
('a', 'b', 'c') (Char, Char, Char)
[(False, 'O'), (True, '1')] [(Bool, Char)]
([False, True ], ['0', '1']) ([Bool], [Char])
[tail , init, reverse] [[a] -> [a]]

Types of functions

What are the types of the following functions?

  • second xs = head (tail xs)
  • swap (x , y) = (y, x)
  • pair x y = (x , y)
  • double x = x ∗ 2
  • palindrome xs = reverse xs == xs
  • twice f x = f (f x)

Hint
Take care to include the necessary class constraints if the functions are defined using overloaded operators.

Functions Types
second xs = head (tail xs) second :: [a] -> a
swap (x , y) = (y, x) swap :: (a,a) -> (a,a)
pair x y = (x , y) pair :: a -> a -> (a, a)
double x = x ∗ 2 double :: Num a => a -> a
palindrome xs = reverse xs == xs palindrome :: Eq a => [a] -> Bool
twice f x = f (f x) twice :: (a -> a) -> a -> a

Check with HUG

Check your answers to the preceding two questions using Hugs.

Functions Types Result HUG
second xs = head (tail xs) second :: [a] -> a OK
swap (x , y) = (y, x) swap :: (a,a) -> (a,a) OK
pair x y = (x , y) pair :: a -> a -> (a, a) OK
double x = x ∗ 2 double :: Num a => a -> a OK
palindrome xs = reverse xs == xs palindrome :: Eq a => [a] -> Bool OK
twice f x = f (f x) twice :: (a -> a) -> a -> a OK

Questions

Why is it not feasible in general for function types to be instances of the Eq class?

All i can think of to answer this is: To check if two functions are equals, you need to be able to enumerate all input parameters possibles then check for the functions to compare that for each same input, this gives the same result.

Depending on the starting set of applications, this can be impossible (e.g. the set of natural number is infinite).

When is it feasible?
Hint
Two functions of the same type are equal if they always return equal results for equal arguments.

If we work with functions that takes as input a small finite set of data, this can be possible.

Source

Latest posts