September 1, 2026

Haskell for Hobos -- Map and Filter

These are my 2 favorite routines for working with lists.

Routines like this are why you don't need loops in Haskell. You have prefabricated higher level ways of dealing with lists. Many (most?) times when you are using a "for" loop in some other language you are cranking an index variable (often named "i") from 1 to N. Why not just get rid of that -- let the language do the work for you? A good step in that direction is something like a "foreach" interator that runs through a list or some collection.

Map

What map does is to run through a list, and apply the function you give it to each element, then gather the results into a new list.
ll = [1,3,7,99]
xx = map show ll
main = putStrLn $ show xx
-- yields:  ["1","3","7","99"]
Here "show" is a function that converts most anything (or tries to) into a string. We map it over the list ll, converting each integer in the list into a string. We need to use show again to print the list -- the function "putStrLn" expects a string argument, not a list.

Filter

Filter also applies a function to every element of a list. What it does is to use the function to select elements to keep. Elements that pass the test go into a new list. The function must accept whatever type is in the list and return True or False (a Bool).
lll = [1,3,8,99]
main = putStrLn $ show $ filter isOdd lll
-- yields:  [1,3,99]
Note here the use of the "$" operator (function). putStrLn expects a single argument and will just grab "show" without the dollar sign. The dollar sign effectively says, "completely do all the stuff to the right of the dollar sign first" then gives the result to PutStrLn. This is typical Haskell.

map and filter in other languages

Python (as an example) has map and filter that provide the same functionality, as do other languages. In fact many mainstream imperative languages have incorporated these and other routines from functional languages.

Ruby has both map and filter (and provides "select" as a synonym for filter). Javascript has them too. C# has the functionality but with different names (typical Microsoft).


Have any comments? Questions? Drop me a line!

Tom's software pages / tom@mmto.org