Reputation: 33
I am trying to implement a basic function but I'm out of practice with Haskell and struggling so would really appreciate some help. My question is specifically how to select a section of a list by index. I know how to in other languages but have been struggling
[ x | x <- graph, x!! > 5 && x!! <10 ]
I have been fiddling around with basic list comprehension similar to what is above, and while I know that isn't right I was hoping a similarly simple solution would be available. If anyone wants more information or felt like helping on the further question I have included more information below, thanks!
type Node = Int
type Branch = [Node]
type Graph= [Node]
next :: Branch -> Graph -> [Branch]
This is the individual question for the "next" function
Apologies for the two pictures but it seemed the best way to convey the information.
Upvotes: 3
Views: 437
Reputation: 4219
As pointed out in the comments !!
does not give you the index of a value in the way it seems you expect. It is just an infix for getting an element of a list.
There is no way to get the index of x
like this in Haskell since the x
object doesn't keep track of where it is.
To fix this we can make a list of objects that do keep track of where they were. This can be achieved with zip
.
zip [0..] graph
This creates a list of tuples each containing their index and the value in graph
.
So you can write your list comprehensions as
[ x | (index, x) <- zip [0..] graph, index > 5, index < 10 ]
Now this is not going to be terribly fast since it still needs to go through every element of the list despite the fact that we know no element after the 11th will be used. For speed we would want to use a combination of take
and drop
.
drop 5 (take 10 graph)
However if we wanted to do some other selections (e.g. all even indexes), we can still go back to the list comprehension.
Upvotes: 1
Reputation: 804
In this case, you could drop 5 <&> take 4
. As in drop 5 x & take 4
. Drop skips the first few elements and take leaves out all but the first few left after the drop.
Upvotes: 0