Solve the following problems in Haskell.
Write a function last
that returns the last element
of a list.
> last [2, 4, 6, 8] 8
Write a function secondLast
that returns the
second-to-last element of a list.
> secondLast [2, 4, 6, 8] 6
Implement the built-in function zip
that converts two
lists into a list of pairs:
> zip [10, 12, 14] [21, 23, 25, 27] [(10,21),(12,23),(14,25)]
Stop zipping when you reach the end of either list.
Implement the built-in function unzip
that converts a
list of pairs into a pair of lists:
> unzip [(10,21),(12,23),(14,25)] ([10,12,14],[21,23,25])
Write a function flatten
that flattens a list of
lists into a single list:
> flatten [[2, 4], [6, 8], [10]] [2, 4, 6, 8, 10]
Implement the built-in function reverse
that reverses
a list:
> reverse [2, 4, 6] [6,4,2]
Your function should run in linear time.
Construct a list ints
of integers from 1 to ∞,
without using the built-in range operator (i.e. [1 ..
]
).
Implelement the built-in function cycle
that takes a
list L and returns an infinite list consisting of L repeated over and
over:
> take 10 (cycle "abc") "abcabcabca"
Consider these definitions:
infinite x = infinite x second a b = if b > 0 then b else a rep x = x : rep x
Which of these queries will terminate?
infinite 0
second (infinite 0) 5
length (take 3 (rep (infinite 0)))
Write a function isPrime
that determines whether an
integer is prime.
Write a function dedup
that eliminates consecutive
duplicate elements in a list:
> dedup [2, 4, 4, 4, 6, 6, 8, 4] [2, 4, 6, 8, 4]
Write a function combine
that groups consecutive
duplicates into sublists:
> combine [2, 4, 4, 4, 6, 6, 8, 4] [[2], [4, 4, 4], [6, 6], [8], [4]]