imka
imka

Reputation: 53

What's the difference between 1 :| [2, 3, 4] and [1, 2, 3, 4] in Haskell

I'm learning Haskell, one of the best functional-programming language. I've got roadblocks during my studies with the list. As I figured out there are two possibilities to write a list - just wrap using []. or use a NonEmpty list. What's the difference between these variants and what's better to use and why?

Upvotes: 4

Views: 639

Answers (1)

Mark Seemann
Mark Seemann

Reputation: 233317

[1,2,3,4] is actually syntactic sugar for

Prelude> 1:2:3:4:[]
[1,2,3,4]

The [] type has two data constructors: : and []. You use : to 'cons' a value to an existing list. The empty list [] is the base case, so in order to be able to create a finite list, you'll have to terminate the 'cons chain' with an empty list, as in the above example.

In other words, while [1,2,3,4] is one valid example of a list, so is []. Lists can be empty.

As the name implies, NonEmpty can't be empty. It has only one data constructor: :|. Thus, the shortest list you can express using NonEmpty is a singleton list:

Prelude Data.List.NonEmpty> 1 :| []
1 :| []

While the right-hand side of :| does accept an empty list ([]), you must supply a value for the left-hand side (in the above example 1). Thus, a NonEmpty list will always contain at least one element.

These properties are guaranteed at compile time, so if you need a non-empty list, use NonEmpty, and if you need a list that may be empty, use [].

Upvotes: 4

Related Questions