Programming in Haskell exercises (1)
Working on exercises of Chapter 1 Introduction
Published in
3 min readDec 30, 2019
Change terminal prompt and ghci prompt. Let ghci support multiple lines.
% export PS1="👍 "
👍 cat ~/.ghci
:set prompt "λ: "
:set +m
:set prompt-cont " | "
👍 ghci
GHCi, version 8.2.1: http://www.haskell.org/ghc/ :? for help
Loaded GHCi configuration from /Users/zhijunsheng/.ghci
λ:
- Give another possible calculation for the result of
double (double 2)
.
λ: double x = x + x
λ: double 2 + double 2
8
λ: double (double 2)
8
2. Show that sum [x] = x
for any number x
.
λ: sum [5]
5
λ: sum [1024]
1024
3. Define a function product
that produces the product fo a list of numbers, and show using your definition that product [2,3,4] = 24
.
λ: let
| product' :: Num a => [a] -> a
| product' [] = 1
| product' [n] = n
| product' (n:ns) = n * product' ns
|
λ: product' []
1
λ: product' [7]
7
λ: product' [2,3,4]
24
Another way to do multi line is using :{ and :}, like this:
𝜆: :{
Prelude| prod :: Num a => [a] -> a
Prelude| prod [] = 1
Prelude| prod [n] = n
Prelude| prod (n:ns) = n * prod ns
Prelude|
Prelude| :}
𝜆: prod []
1
𝜆: prod [7]
7
𝜆: prod [2,3,4]
24
4. How should the definition of the function qsort
b modified so that it produces a reverse sorted version of a list?
λ: let
| qsort :: Ord a => [a] -> [a]
| qsort [] = []
| qsort (x:xs) = qsort larger ++ [x] ++ qsort smaller
| where smaller = [y | y <- xs, y <= x]
| larger = [y | y <- xs, y > x]
|
λ: qsort "Golden Thumb"
"uonmlhedbTG "
λ: qsort [3,5,1,0,-2,9]
[9,5,3,1,0,-2]
λ: qsort "Good morning"
"rooonnmigdG "
5. What would be the effect of replacing ≤
by <
in the original definition of qsort
? Hint: consider the example qsort [2,2,3,1,1]
.
λ: let
| qsort :: Ord a => [a] -> [a]
| qsort [] = []
| qsort (x:xs) = qsort smaller ++ [x] ++ qsort larger
| where smaller = [y | y <- xs, y < x]
| larger = [y | y <- xs, y > x]
|
λ: qsort "Good morning"
" Gdgimnor"
λ: qsort [2,2,3,1,1]
[1,2,3]
λ: qsort "Good morning"
" Gdgimnor"
There is no duplication in the result list.