dmcdo
dmcdo

Reputation: 13

Is there a clean way to get the head AND tail of a list in a single expression?

Is there something equivalent to

(\(x : xs) -> (x, xs)) theList

built into the language, to where I could write something like

let (h, t) = headAndTail theList in h : t

?

Upvotes: 1

Views: 159

Answers (2)

Daniel Wagner
Daniel Wagner

Reputation: 152837

Plain old pattern bindings fit the bill.

let h:t = theList in h : t

Upvotes: 4

chepner
chepner

Reputation: 531205

Data.List provides uncons :: [a] -> Maybe (a, [a]):

> uncons "foo"
Just ('f', "oo")

If you really want a partial function of type [a] -> (a, [a]), you can compose with Data.Maybe.fromJust.

Upvotes: 5

Related Questions