Join egghead, unlock knowledge.

Want more egghead? It's 45% off for a limited time only!

This lesson is for members. Join us? Get access to all 3,000+ tutorials + a community with expert developers around the world.

Unlock All Content for 45% Off

Already subscribed? Sign In

Save 45% for a limited time.

Get access to all courses and lessons on egghead today.

Autoplay

    Represent Absent Data with Elm’s Maybe Type

    Enrico BuonannoEnrico Buonanno

    An important union type of the Core library, Maybe is used to represent the possible absence of data.

    Follow along the documentation at package.elm-lang.org/packages/elm-lang/core/latest/Maybe and download the Elm REPL from elm-lang.org/. If you'd like to try it out in your browser I've provided a link to the Elm repl here.

    elmElm
    Code

    Code

    Become a Member to view code

    You must be a Member to view code

    Access all courses and lessons, track your progress, gain confidence and expertise.

    Become a Member
    and unlock code for this lesson
    Transcript

    Transcript

    00:00 Another very important union type in the core library is the Maybe type. This is the definition as you can see it in the documentation.

    00:09 You can see that the Maybe type has two constructors, Nothing -- this takes no parameters because it means that there's nothing there -- and Just a -- this means that we have a Maybe a that indeed does contain a value of type a. a is a type parameter, so this can be used with any type.

    00:30 To see an example of this, let me switch to the terminal and start the Elm REPL. Let me show the function head in the list module. The REPL is telling me that this is a function that takes a list of a and returns a Maybe a.

    00:46 For example, let's have an empty list. Let's call this l1. Let this be an empty list. Now, if I take the head of l1, you can see that this is nothing. It's actually an empty Maybe. Let me now have another list, l2, which contains a couple of numbers.

    01:06 If I now get the head of l2, then indeed we have the first element wrapped in a Just. To a certain extent, you could see Maybe as being able to represent success or failure. If you get a Nothing, in a sense it's failure because you didn't get any data. If you get a Just, then you did get some data.

    Discuss

    Discuss