DEV Community

Discussion on: What's a useful programming language feature or concept that a lot of languages don't have?

Collapse
 
avalander profile image
Avalander • Edited

Pattern matching as done in ML languages.

factorial :: Int -> Int
factorial 0 = 0
factorial 1 = 1
factorial n = n * (factorial (n - 1))
Enter fullscreen mode Exit fullscreen mode

I think it's a much more elegant way to handle end conditions and special cases than if statements and it makes the code much easier to reason about.

It is also awesome when used in conjunction with union types.

data Pony = Pegasus String Int
  | Unicorn String String
  | EarthPony String

applejack = EarthPony "Applejack"
twilight = Unicorn "Twilight Sparkle" "levitation"
rainbow = Pegasus "Rainbow Dash" 20


f :: Pony -> String
f (Pegasus name speed) = name <> " flies at " <> (show speed) <> "mph"
f (Unicorn "Twilight Sparkle" _) = "Twilight Sparkle is an Alicorn now, get over it!"
f (Unicorn name spell) = name <> " casts " <> spell
f (EarthPony name) = name <> " is a nice pony"
Enter fullscreen mode Exit fullscreen mode

If I had ever understood lisp's macros I would probably mention them here too.

Collapse
 
rhymes profile image
rhymes

Pattern matching, really loved it when I came across it in Erlang. Should brush up on declarative languages