1

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.

1
  • If you know that you want exactly 2 results, then it is better to use a 2-tuple rather than a 2-element list. e.g. (1,4) instead of [1,4] Commented Mar 20, 2012 at 23:44

3 Answers 3

6

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]
Sign up to request clarification or add additional context in comments.

2 Comments

With that pattern matching, it would seem reasonable to also add the case firstLast3 [x] = [x].
@leftaroundabout - possibly, although there's an open question as to whether the intended behavior is firstLast3 [x] = [x] or firstLast3 [x] = [x,x]. If the latter, it may also make sense to change the return type to a Maybe [a].
2

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]

5 Comments

Why the Num constraint? I also think it would be more useful to have a function headAndLast :: [a] -> Maybe [a]. Composition with sequence may be the most convenient way to do this.
That Num constraint is weird; why do you need it? Also, some hacks you may or may not enjoy: lastM = headM . reverse; headAndLast' :: [a] -> Maybe [a]; headAndLast' = liftM2 (\x y -> [x,y]) headM lastM.
Daniel, looks like type of liftM2 (\x y -> [x,y]) headM lastM is [Maybe a], but not Maybe [a]
I'm not sure why you would prefer Maybe [a] over Maybe (a,a).
@pat, topic-starter want to get [1,4] from [1,2,3,4], not (1,4).
0
let xs = [1, 2, 3, 4] in [head xs, last xs]

1 Comment

As John L. mentioned above, that version will fail if xs is [].

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.