Defining Functions, List Comprehension
1. safetail Consider the function safetail that behaves in the same way as tail,
except that safetail maps the empty list to the empty list, whereas tail gives
an error in this case. Give variants safetail1, safetail2, safetail3 using
a) a conditional expression
b) guarded equations
c) pattern matching
2. Definition of OR Give an implementation of OR
(|||) :: Bool -> Bool -> Bool
using only two equations. [Note we are using ||| instead of || as the latter is
predefined in Haskell. There are various possibilities to do so (see lecture notes,
handout 4), however, try to do it in a way that for some inputs it can give already
a result when Haskell has read the first argument.
3. List Comprehension. Using list comprehension define
1. a list with the first 1000 square numbers and a list with all squares up to
1000.
2. a list with numbers between 10 and 100 that are not divisible by 7.
3. all numbers between 100 and 200 that are palindromes [and not divisible by
7].
Hints: 1) Start with easier expressions: what does
test0 = [x+1 | x <- [1..10]]? Hint 2) To transform a number n into a string use show n. Example for use of show: appendToItself n = (show n) ++ (show n) 4. List Comprehension We want to find all triples (x,y,z) fulfilling the property x2 + y2 = z2. As there are infinitely many only look at those with numbers x,y,z less than or equal to a given number n. So, we look for a function that maps a given number n to the list of such triples; its type is: Int -> [(Int,Int,Int)]
Hint: Have a look at slide 3 from chapter 5. Then build the generators, and add
the property above as guard. The equation is one line.
2