Better case syntax

I saw this github issue and i think its a good idea:

instead of this:

func value =
    case doThing value of
        Just n -> n + 1
        Nothing -> 0

you can do this instead:

func =
    doThing >> case
        Just n -> n + 1
        Nothing -> 0

with this syntax, you don’t need to choose as many variable names, which reduces shadowing errors. it is also a less redundant syntax that doesn’t create as much “noise” in the code, which improves readability.

also maybe the existing syntax (case value of) should be replaced with value |> case so that we don’t end up making elm more complicated

I’ve occasionally wanted something like this. However, I find that I can get something pretty close by defining a separate function. In my own personal style, I already tend to isolate case expressions to their own standalone functions so that works pretty well for me.

func =
  doThing >> innerFunc

innerFunc value =
  case value of
    Just n -> n + 1
    Nothing -> 0

For what it’s worth, you can do this in PureScript using the _ placeholders

func ∷ Int → Int
func = case doThing _ of
  Nothing → 0
  Just n → n + 1

But in Elm, if you’re dealing with Maybe (or Result or Either or any of the other types where there are more fully-fleshed-out APIs), you’ll probably have some combinators to help you do it point-free or the like.

import Maybe.Extra as Maybe

func : Int -> Int
func = Maybe.unwrap 0 ((+) 1) << doThing

So this is basically the same as LambdaCase in Haskell which I think is definitely useful. But, I would be amazed is this were ever accepted into Elm on purely philosophical grounds. Haskell has its language flags to allow this sort of thing to be switched on, but in general it seems that Elm’s guiding principle is to only include syntax that is necessary. We have seen extraneous syntax removed from Elm over the years and while this would be nice - it certainly isn’t necessary.

1 Like

If this case syntax is considered useless then I wouldn’t be surprised if >> and << get removed

You know I wouldn’t be 100% surprised either! I’d be very disappointed. But I don’t quite see that in the same light in that those operators are not really syntactic sugar, they are fundamental to function composition. It seems like there is a clear intent over the years to limit the syntax in the language so I just think that despite its merits, your idea is unfortunately a bit unlikely to get much traction.

1 Like

This topic was automatically closed 10 days after the last reply. New replies are no longer allowed.