This week we began our study of the Haskell language. In addition to following our lectures, I recommend that you read chapters from our textbook Learn You a Haskell For Great Good! by Miran Lipovača, which is freely available online.
In this class we will use GHC (the Glasgow Haskell Compiler). You will want to download and install it now.
This week we discussed
integers (types Int and
Integer), including operators +
, -
, *
,
div
, mod
booleans (type Bool), including
operators &&
, ||
, not
comparison operators ==
,
/=
, <
, <=
, >
,
>=
if
/ then
/ else
expressions
function definitions
type declarations
pattern matching in function definitions
lists, including the list
constructor :
and the concatenation operator ++
characters (type Char) and strings (type String = [Char])
basic built-in list functions:
head
, tail
, length
, take
type variables in type declarations
the Eq type class
ranges
You can review these features in chapters 1-4 of the Learn You a Haskell book.
Here are some of the functions we wrote in the tutorial.
Write
a function kth
that
returns the kth element of a list, where elements are numbered
starting from 0. (Do not use the built-in operator !!
,
which does the same thing.)
kth :: Int -> [a] -> a kth 0 (x : _) = x kth n (_ : xs) = kth (n - 1) xs
Construct a list ints
of integers
from 1 to ∞.
-- intsFrom n returns an infinite list of all integers starting with n -- i.e. [n, n + 1, n + 2, ...] intsFrom :: Int -> [Int] intsFrom n = n : intsFrom (n + 1) -- a list of all integers starting with 1 allInts :: [Int] allInts = intsFrom 1
Implement
the built-in function cycle
that
takes a list L and returns an infinite list consisting of L repeated
over and over.
my_cycle :: [a] -> [a] my_cycle xs = xs ++ my_cycle xs