Haskell introduction
Haskell introduction
Haskell is a functional language, which means that the fundamental computational paradigm consists
of functions that provide mappings from inputs to outputs:
Functional programs consist of many smaller functions that are chained or composed. Iteration is
accomplished using recursion. To effectively use Haskell, you must shift away from thinking about how
the machine should solve your problem (as you had to with procedural programming) and focus on
defining the solution to the problem in a mathematically rigorous way.
In Haskell, variable bindings are permanent and all types are statically bound at compile time. Haskell
programs are stateless, and I/O is accomplished using special wrappers to encapsulate the side effects.
Functions are evaluated using lazy (or non-strict) evaluation.
In this lab, we will use ghci, which is an interactive interpreter for Haskell (similar to irb for Ruby).
Because of the lack of traditional procedural I/O in Haskell, we will concentrate on writing functions
rather than programs.
1. Start ghci and get the prompt Prelude>. When you need to, you can exit ghci by entering the
end-of-file keystroke Control-D at the prompt.
2. Try evaluating various Haskell expressions, such as:
reverse [1,2,3,4,5]
reverse "Haskell"
show 17
show [1,2,3,4]
[22..47]
take 15 [22..47]
drop 15 [22..47]
1 : [2,3,4]
['h','e','l','l','o']
'h' : "ello"
[1,2,3,4] ++ [40,50,60,70]
[2,3,4] ++ [1]
import Data.List
sort [80, 38, 23, 40, 70, 24, 8, 92, 78, 80, 42, 19, 95, 87, 4]
reverse "ABC"
reverse
:type reverse
Programs:
1. Hello World
main :: IO ()
2. Factorial Function
factorial 0 = 1
factorial n = n * factorial (n - 1)
main :: IO ()
fibonacci 0 = 0
fibonacci 1 = 1
main :: IO ()
4. List Comprehension
squares :: [Integer]
main :: IO ()
5. QuickSort Algorithm
quickSort [] = []
quickSort (x:xs) = quickSort [y | y <- xs, y <= x] ++ [x] ++ quickSort [y | y <- xs, y > x]
main :: IO ()
6. Write a list comprehension that produces all the numbers between 1 and 100 that are multiples
of 2, 3, and 5.
7. Write a list comprehension to generate all the pairs of numbers between 1 and 20 that add up to
20.