Joseph Haugh
University of New Mexico
v :: T
, where v
is a value and T
is a type when writing a type signaturev
has type T
A function is denoted by a −>;
A function T −> U
means a function takes as an argument a value of type T
and returns a value of type V
Function Examples
add1 :: Int -> Int
add1 x = x + 1
notNot :: Bool -> Bool
notNot b = not (not b)
A type error occurs when a function receives a type it doesn’t expect
For example:
2 * True
This throws an error because (*) expects two numbers not a number and a Bool
In ghci you can inspect the type of a value using or
ghci> not True
False
ghci> :t not True
Bool
[[Int]]
means list of Ints[[Bool]]
means list of list of Boolsghci> :t [1,2,3]
[Int]
ghci> :t [True, False]
[Bool]
ghci> :t [1,True]
Error: Cannot have list with Int and Bool
(Int, Float)
means a tuple of an Int and a Float(Int, Float, Bool)
means a tuple of an Int, Float and a Boolghci> :t (1,False)
(Int, Bool)
ghci> :t (False,1)
(Bool, Int)
ghci> :t ((1,False),1.0)
((Int, Bool),Float)
ghci> f = \x -> x + 1
ghci> f 1
2
ghci> g = \b -> not b
ghci> g True
False
Non curried function:
prod :: (Int, Int) -> Int
prod (x, y) = x * y
Curried version:
prod :: Int -> Int -> Int
prod x y = x * y
Can be thought of as:
prod :: Int -> (Int -> Int)
prod x y = x * y
Or more explicitly:
prod :: Int -> (Int -> Int)
prod = \x -> (\y -> x * y)
Curry Examples Non curried three arg function:
add3 :: (Int, Int,Int) -> Int
add3 (x, y, z) = x + y + z
Curried version:
add3 :: Int -> Int -> Int -> Int
add3 x y z = x + y + z
Explicit Version:
add3 :: Int -> (Int -> (Int -> Int))
add3 = \x -> (\y -> (\z -> x + y + z))
Write out the curried and explicit versions of the following function:
foo :: (Int, String, Float) -> Int
foo (x, s, f) = x
Write out the curried and explicit versions of the following function:
foo :: (Int, String, Float) -> Int
foo (x, s, f) = x
foo :: Int -> String -> Float -> Int
foo x s f = x
foo :: Int -> (String -> (Float -> Int))
foo = \x -> (\s -> (\f -> x))