Skip to content

Instantly share code, notes, and snippets.

@marcmartino
Created June 15, 2021 23:17
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save marcmartino/70cce4b5ab122c8fd8c10491d75f6991 to your computer and use it in GitHub Desktop.
Save marcmartino/70cce4b5ab122c8fd8c10491d75f6991 to your computer and use it in GitHub Desktop.
Less contrived pattern matching II

Less Contrived Pattern Matching Example II

Another example of a nice use of pattern matching I came upon while practicing basic hs- pattern match over a tuple of two booleans that you're creating ad hoc. This is great because it avoids the nesting of ifs/ternaries and is more clear what's going on.

getClassification :: Int -> Int -> Classification
getClassification target aliquotSum =
  case (target > aliquotSum, target < aliquotSum) of
    (True, _) -> Deficient
    (_, True) -> Abundant
    _ -> Perfect

In javascript we might write it thusly:

const getClassification = (target, aliquotSum) => 
  return target > 'aliquotSum' 
      ? 'Deficient'
      : target < aliuotSum 
      ? 'Abundant' 
      : 'Perfect'

or in python:

def getClassification(target, aliquotSum):
  if (target > aliquotSum):
    return 'Deficient'
  if (target < aliquotSum):
    return 'Abundant'
  return 'Perfect'
@marcmartino
Copy link
Author

first example here

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment