Home > Back-end >  Is there a clean way to get the head AND tail of a list in a single expression?
Is there a clean way to get the head AND tail of a list in a single expression?

Time:04-09

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

?

CodePudding user response:

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.

CodePudding user response:

Plain old pattern bindings fit the bill.

let h:t = theList in h : t
  • Related