Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Empty list vs Maybe to represent failed computation in Haskell

Tags:

haskell

maybe

Over at the Edx Haskell course, Erik Meijer repeatedly states that using the Maybe type for failed computations is not something one should do; instead, one should use the empty list for that.

My understanding is that the Maybe type is a good thing and that we should use it. However, it seems that a list can model everything a Maybe can model and more... So why do we need the Maybe type at all?

like image 368
user3139545 Avatar asked Nov 24 '14 10:11

user3139545


People also ask

Can you have an empty list in Haskell?

Get Programming with HaskellYou can't return an empty list, because an empty list is the same type as the elements of the list.

How does maybe work in Haskell?

The maybe function takes a default value, a function, and a Maybe value. If the Maybe value is Nothing , the function returns the default value. Otherwise, it applies the function to the value inside the Just and returns the result.

What does NS mean in Haskell?

The sequence (n:ns) is a shorthand for head - tail. Quite literally, the first value, the head, is called n and the remained are the other, potentially plural, n s, which is why it is called ns . Haskell has pattern matching.


1 Answers

However it seems that a list can model everything a Maybe can model and more

The "and more" is an excellent reason to use Maybe. As a consumer of a list, you need to be able to handle zero, one or multiple values. As a consumer of a Maybe, you only need to be able to handle zero or one values. So in cases where multiple values don't make sense, it is much better to use Maybe so that you know statically that you won't get nonsensical values.

like image 189
GS - Apologise to Monica Avatar answered Sep 23 '22 04:09

GS - Apologise to Monica