Reputation: 989
I'm new to Haskell so I apologize if this is an easy question, but I couldn't find an answer anywhere.
What I would like to do is grab the first and last element of a list and return those in a new list.
I know that head [1,2,3,4]
will return 1
, and I know that last [1,2,3,4]
will return 4
. But how would I go about placing those two results into a list such as: [1,4]
?
Thanks.
Upvotes: 1
Views: 1612
Reputation: 21990
Maybe you want to look at Maybe to avoiding empty list case.
headAndLast :: [a] -> Maybe [a]
headAndLast [] = Nothing
headAndLast x = Just [head x, last x]
And
> headAndLast [1,2,3]
Just [1,3]
Upvotes: 2
Reputation: 28097
You can place elements into a list using list notation syntax:
firstLast1 xs = [head xs, last xs]
which is syntactic sugar for using the list constructor directly:
firstLast2 xs = head xs : last xs : []
However, both of these will fail with a runtime error when an empty list is passed. You can guard against this by pattern-matching:
firstLast3 [] = []
firstLast3 xs = [head xs, last xs]
Upvotes: 6