In this section we learn some very basic list operations.
Lists of elements are one of the most primitive and most useful value types in Haskell. A list is simply a sequence of zero or more elements of the same type. These are defining characteristics of a list:
We can create a list in two ways:
[4, 6, 1, 2]. A special notation ['a'..'g'], called enumeration, allows us to form a list of all values from a specific value to another.x:xs. Here x is the new element, and xs is the list of existing elements. For instance the list [1, 2] can be written as 1:[2] or also as 1:2:[]. In this way lists are a little like linked lists in other languages.There are many built-in functions that work on lists. They are all part of what is known as “Standard Prelude”, and most can be seen in appendix B.8 from the book. You can also access the online documentation, though that takes a bit getting used to.
headtailtaken and a list, returns the first n elements from the list.
dropn and a list, returns the remaining of the list after the first n elements are removed.
lengthsumproduct++reverseHere are some example uses (recall that function application does not require parentheses):
head [4..6] -- Returns 4
tail [1..3] -- Returns [2, 3]
take 3 [1..10] -- Returns [1, 2, 3]
length "abc" -- Returns 3. Strings are lists of characters.
length [1..10] -- Returns 10
product [1..5] -- Returns 120
reverse [1..5] -- Returns [5, 4, 3, 2, 1]
Some practice questions:
== to compare two strings).Write functions that accomplish the following:
prefix takes a list and returns the first three elements of the list.isPalindrome takes a string and returns whether the string is a palindrome.addInterest takes two arguments: A “principle” amount, and an interest “rate”. It returns the new amount if we added the appropriate interest.hasEnough takes a number and a list and returns whether the list has at least that many elements.isDoubled takes a list and returns whether the list is the result of appending a list to itself (in other words, if the first half of the lst is exactly equal to the second half).suffix takes a list and returns the last three elements of the list.