[Haskell-cafe] (SPAM 3)Re: handling NULL value in database query with Maybe (or other ...)

Ian Denhardt ian at zenhack.net
Tue Dec 18 18:59:15 UTC 2018


Quoting Damien Mattei (2018-12-18 10:34:15)

> if (x == NULL)
>    printf("NULL\n");
> else
>    printf("%s",*x);

C will also allow you to just write:

    printf("%s", *x);

Without the if, which will silently compile without complaint, and then
segfault (at best) or corrupt memory at runtime. With Maybe there's no
way to try to access the value if it isn't actually there.

As others have pointed out, your database has a concept of null (to
which the article's complaints are spot on), so somehow you have to
model the fact that it may not actually return a string.

There are more ergonomic ways of dealing with it than having the same
case expression everywhere; other replies suggested using the `maybe`
function to supply a default, or modifying the database schema to say
NOT NULL -- but you have to deal with it somehow. The advantage of Maybe
is:

* It makes the possibility of no-value explicit, and not something you
  can forget to handle.
* It makes it possible to express that no-value is *not* a possibility,
  when that is the case (by just not using a Maybe).

-Ian


More information about the Haskell-Cafe mailing list