This week in Haskell I have started to look at two new aspects of Haskell programming that relate to list manipulation (surprise, surprise). These functions are map and filter.
Map:
Maps are very interesting because they are a quick and useful way to apply a function to each element of any list. For example if we had a simple list such as [1,3,5,7,9] and we wanted to add 1 to each of these values instead of looping through the list with a for loop, adding one to each value (i+1) and returning the list with the new values we can do this very quickly in Haskell (with one simple line).
For example:
In this example I used a list of all Integers and mapped a function that added the Integer 1 to each element. Mapping can also be done to lists of type String. If we had a list of Strings such as ["Name", "Age","Sex",Social Security Number"] and I decided after the fact that I wanted at add a colon at the end of each element. Using a map this is how that could be done:
The syntax is done by using the map operation and then the "++" characters (which is the String concatenation operand in Haskell) and then placing the character we wish to append to the end in quotes (in our case ":"). We can see that we now have the output:
Filters while similar to maps work by checking each element in list independently and seeing if it fits the criteria of the specified function. If the element falls into the criteria (the boolean True is assigned) it is added to a new list that will be returned once every element has been tested If an element does not fit the criteria of the function, it is not added to the final list that is returned. And it can be said to have been "filtered" out.
For example:
Say we have a list of elements [1,10,2,11,3,12,4,13,5,14] and we want to filter through this list and only return all the integers that are greater than or equal to 10. This can be done using a filter like so:
This would print out the desired output of a list that contains only elements that are 10 or greater. Output:
This is a very useful feature in Haskell since most things that we will be aiming to do involve lists in some way or another.
Stay tuned for more updates on my progress with Haskell!
No comments:
Post a Comment