Chapter 6 introduced lists, and now you will learn another way to represent a list. Do you remember how sets are represented using mathematical symbols? Well, you will do that with lists. Further, you will learn more complex functions that you can apply on lists.
Introduction
This type of representation is called list comprehension , and x is called a generator.
Observe that we added two predicates, separated by a comma.
In this case, every element from the first list is summed up with every element from the second list. It is similar to a Cartesian product , but in this case you sum up the elements of pairs in the Cartesian product.
This means every element of the list is replaced by 0. Instead of _, you could use a variable, but it is more convenient in this way, as syntactic sugar. For short, syntactic sugar is just another representation for expressions written in an analytic way and does not add functionality. The main purpose of syntactic sugar is to make the code more readable.
Now it is better. The show function converts its parameter into a String.
Other Functions on Lists
Now that you know how to work with functions, you’ll write your own functions to apply on lists. You will start by using some other functions from the Data.List module (all other functions on lists that you have learned about so far belong to this module), and then you will sort elements on a list of integers.
find returns the first element of the list that satisfies a predicate, or Nothing otherwise.
filter returns all elements of the list that satisfy a condition.
elemIndices/elemIndex returns all indices of the elements equal to a given item or the first index of the element equal to a given item or Nothing if there is no such element.
findIndex/findIndices returns all indices of the elements that make up a predicate or the first index of the element that makes up a predicate or Nothing if there is no such element.
The zip family of functions creates tuples from lists based on different criteria.
Go ahead and practice these functions.
Summary
How to represent a list in a comprehension form
How to apply your own functions on lists
Other useful functions applied on lists
How to sort a list, using the quicksort algorithm
References
- 1.
T. H. Cormen, C. E. Leiserson, R. L. Rivest, and C. Stein, Introduction to Algorithms (MIT Press, 2009)
- 2.
A. Nunes-Harwitt, M. Gambogi, and T. Whitaker, “Quick-Sort: A Pet Peeve” in proceedings of the 49th ACM Technical Symposium on Computer Science Education, pp. 547–549 (ACM, 2018)
- 3.
M. Lipovaca, Learn You a Haskell for Great Good! A Beginner’s Guide (No Starch Press, 2011)
- 4.
M. Aslam, Functional Programming Language–Haskell (2003)
- 5.
- 6.
List comprehension, https://wiki.haskell.org/List_comprehension