Will
Will

Reputation: 989

Build List From Functions In Haskell

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

Answers (3)

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

John L
John L

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

sykloid
sykloid

Reputation: 101356

let xs = [1, 2, 3, 4] in [head xs, last xs]

Upvotes: 0

Related Questions