Remix.run Logo
jbreckmckye 2 days ago

Now that we have defined a language without booleans, we need some way to coalesce these optional values

We ideally want an infix function that can reduce the "truthiness" of two values.

Let us imagine this language is a Haskell-type-thing, and we can define pseudo-operators with pattern matching

    infixr 3 &&
    (&&) :: Optional -> Optional -> Optional
    Empty && _       = Empty
    _ && Empty       = Empty
    Some A && Some B = Some A
    _ && _           = Empty

    infixr 2 ||
    Some || _     = Some
    None || Some  = Some
    None || None  = None
    _    || _     = None 
Hmm, let's see how that looks

    a = b && c
    d = e || f
The good news is that we are free from the tyranny of booleans. The bad news is that we just reinvented JavaScript :-)
kmill 2 days ago | parent | next [-]

That second operator is the <|> operator, from the Alternative typeclass.

The first one has some arbitrariness (do you take the left or right value if both are Just). But, thankfully the Applicative typeclass gives both <* and *>, which lets you choose which value you want:

  Just A <* Just B = Just A
  Just A *> Just B = Just B
(There's the possibility to merge values too, with f <$> Just A <*> Just B, which evaluates to Just (f A B). I feel like this is a "don't try to understand it, just get used to it" sort of syntax. It can be pretty convenient though.)
zahlman 2 days ago | parent | prev | next [-]

> The bad news is that we just reinvented JavaScript :-)

There's a whole lot more to JavaScript typing that makes it JavaScript.

After all, Python does this too (but the spellings are "and" and "or").

Twey a day ago | parent | prev | next [-]

The big difference being that ‘truthiness’ is explicitly encoded next to the value rather than being an inherent property of certain values. That's a win in my book!

BriggyDwiggs42 2 days ago | parent | prev [-]

I honestly really like those two operators in js.

melncat 2 days ago | parent [-]

Don't forget about ?? as well

jbreckmckye 2 days ago | parent | next [-]

I'm a big fan of the Elvis operator myself (.?)

chuckadams 2 days ago | parent [-]

.? is null-safe property access. Elvis is ?:

jbreckmckye 2 days ago | parent [-]

Oh, that makes more sense, because ?: has eyes

https://en.m.wikipedia.org/wiki/Elvis_operator

?:-)

mock-possum a day ago | parent | prev [-]

Mmm nullish coalescing