arliss_obsidian/fp/Language/Functions/Defining/Pattern Matching.md
Orion Kindel 3ee2a9bbbd
update
2024-09-24 17:52:08 -05:00

960 B

Functions may have multiple implementations that change behavior based on the shape of the arguments.

[!tip]- case .. of Pattern matching in function definitions can always be rewritten as case .. of.

isA "a" = true
isA _ = false

can be rewritten as

isA a = case a of
  "a" -> true
  _ -> false

This is similar to method overloading in OOP languages, but differs in that the number of arguments and type of the arguments must be the same for all implementations.

Functions can have any number of implementations, as long as all possible inputs are covered exhaustively.

e.g.

this implementation of Number division has 2 paths:

  • when the denominator is zero, yields Infinity
  • otherwise, performs the division
div num 0.0 = infinity
div num den = num / den

this is equivalent to

div num den =
  if den == 0.0 then
    infinity 
  else
    num / den