I am new to Haskell and am trying to learn the basics. I am having a hard time understanding how to manipulate the contents of a list.
Assume I have the following list and I would like to create a function to subtract 1 from every element in the list, where I can simply pass x to the function, how would this be done?
Prelude>let x = 1:2:3:4:5:[]
Something like:
Prelude>subtractOne(x)
(You can write
1:2:3:4:5:[]more simply as[1,2,3,4,5]or even[1..5].)Comprehensions
You’d like to use list comprehensions, so here it is:
Here I’m using
xsto stand for the list I’m subtracting one from.The first thing to notice is
x <- xswhich you can read as “xis taken fromxs“. This means we’re going to take each of the numbers inxsin turn, and each time we’ll call the numberx.x-1is the value we’re calculating and returning for eachx.For more examples, here’s one that adds one to each element
[x+1|x<-xs]or squares each element[x*x|x<-xs].More than one list
Let’s take list comprehension a little further, to write a function that finds the squares then the cubes of the numbers we give it, so
We need
This means we take the powers
pto be 2 then 3, and for each power we take all thexs fromxs, and calculatexto the powerp(x^p).What happens if we do that the other way around?
We get
Which takes each
xand then gives you the two powers of it straight after each other.Conclusion – the order of the
<-bits tells you the order of the output.Filtering
What if we wanted to only allow some answers?
Which numbers between 2 and 100 can be written as
x^y?Here we allowed all
xand allyas long asx^y<100.Since we’re doing exactly the same to each element, I’d write this in practice using
map:or shorter as
(I have to call it
subtract 1because- 1would be parsed as negative 1.)