Real World Haskell - 第2章 練習問題
Real World Haskell を継続的に勉強中。
Exercises
Chapter 2. Types and Functions
Useful composite data types: lists and tuples
What are the types of the following expressions?
* False
* (["foo", "bar"], 'a')
* [(True, []), (False, 'a')]
Prelude> :type False False :: Bool Prelude> :type (["foo", "bar"], 'a') (["foo", "bar"], 'a') :: ([[Char]], Char) Prelude> :type [(True, []), (False, [['a']])] [(True, []), (False, [['a']])] :: [(Bool, [[Char]])]
Chapter 2
1.Haskell provides a standard function, last :: [a] -> a, that returns the last element of a list. From reading the type alone, what are the possible valid behaviours (omitting crashes and infinite loops) that this function could have? What are a few things that this function clearly cannot do?
2.Write a function lastButOne, that returns the element before the last.
3.Load your lastButOne function into ghci, and try it out on lists of different lengths. What happens when you pass it a list that's too short?
1
- the possible valid behaviours
- リストを受け取り、同じ型の値を 1つ適当に返す
- リストを受け取り、その要素を 1つ返す
- this function clearly cannot do
- it cannot access files; it cannot talk to the network; it cannot tell what time it is.
- 受け取ったリストを別のリストに変換する
2
lastButOne xs = if length xs <= 2 || null xs then take 1 xs else lastButOne (tail xs)
3
Prelude> :load ex2-2.hs [1 of 1] Compiling Main ( ex2-2.hs, interpreted ) Ok, modules loaded: Main. *Main> lastButOne "hoge" "g" *Main> lastButOne "hog" "o" *Main> lastButOne "ho" "h" *Main> lastButOne "h" "h" *Main> lastButOne "" "" *Main> lastButOne [1,2,3,4] [3] *Main> lastButOne [1,2,3] [2] *Main> lastButOne [1,2] [1] *Main> lastButOne [1] [1] *Main> lastButOne [] []