Joseph Haugh
University of New Mexico
Addition:
ghci> 1 + 2
3
Exponentiation:
ghci> 3 ^ 2
9
Integer Division (note the backticks, shift ~):
ghci> 5 ‘div‘ 2
2
Get the first element of a list:
ghci> head [1, 2, 3]
1
Get everything but the first element of a list:
ghci> tail [1, 2, 3]
[2, 3]
Get the nth element of a list:
ghci> [1, 2, 3] !! 2
3
Check if a list contains an element:
ghci> elem 3 [1, 2, 4]
False
Calculate the length of a list:
ghci> length [1, 2, 3]
3
Reverse a list:
ghci> reverse [1, 2, 3]
[3, 2, 1]
Drop the first n elements from a list:
ghci> drop 2 [1, 2, 3]
[3]
Appending two lists:
ghci> [1, 2] ++ [3, 4]
[1, 2, 3, 4]
Sum a list:
ghci> sum [1, 2, 3]
6
Given the following Java Function:
public static int foo(int x, int y) {
return x + (y * 2);
}
You apply it to a set of arguments as follows:
foo(2, 3)
Thus, function application in Java is done with parentheses.
Instead of parentheses Haskell uses a space to denote function application.
For example here is the same function written in Haskell:
foo x y = x + (y * 2)
And here is that function being applied:
foo 2 3
Function application has a higher priority than any other operator.
This means it will always happen first, for example what does the following expression evaluate to?
foo 2 3 * 3
Define a Haskell function, feet2Meters
, which converts a given number of feet to meters. The conversion rate is 1 foot to 0.3048 meters.
For example a function to convert feet to inches could be defined as follows:
feet2Inches ft = ft * 12