Reputation: 141
When working with lists in Haskell, i can simply load my file into ghci and type head list
or last list
to get the information that I need. But if I have a list of lists, lets say: list = [[1,2,3],[4,5,6]]
, how can I get the first element (head) of the first list (in this case, 1), or the last element of the second list (in this case, 6), and so one?
Upvotes: 0
Views: 784
Reputation: 1510
There is an indexing function (!!), so for your examples, head . (!!0) and last . (!!1) . If your question is more general, then please elaborate. Indexing is not great because it can throw errors if you attempt to index past the end of the list, so usually we try to work around that, eg. by saying "well I want to do the same thing to every element of the list so I don't really need the index" (map function) or "if I really do need the index then don't use it directly") (zip [0..], or use of eg. a record data type).
Also, Hoogle is your friend if you've not met it before. If you can break down your functions into simple ones you think might be standard, then search their type signatures, that's usually a good place to start. Hoogle [a] -> Int -> a
even if you don't find exactly what you want, often if you find something similar and browse it's module or source code you can find something helpful.
Upvotes: 1
Reputation: 27225
If all you need is the first or last element, concat
will flatten the list for you.
Upvotes: 1