Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create a nonEmpty list?

Tags:

haskell

I want to use Data.List.NonEmpty, I'm searching how to define a list with one element ? I can only fine nonEmpty with a list, but obviously it returns a Maybe and I don't want that...

Update : I find this solution

let emptyList = 5 :| []
like image 663
Nicolas Henin Avatar asked Mar 05 '26 07:03

Nicolas Henin


1 Answers

fromList takes any non-empty list value.

> fromList [5]
5 :| []

If you want a function of type a -> NonEmpty a, then

singleton = fromList . (:[])

(I'm surprised singleton isn't already in the package.)

(Or as @Lee mentioned in the comments, singleton = pure using the Applicative instance for NonEmpty.)

Your solution of 5 :| [] is also fine, as :| is the way to create a new NonEmpty value; the functions are just wrappers around its use. (In fact, pure is defined as pure a = a :| [], and fromList (a:as) = a :| as.)

like image 188
chepner Avatar answered Mar 08 '26 02:03

chepner