ocaml

how to translate `if b < a` condition to match pattern?


Like the if .. then in code

# let rec range2 a b accum =
  if b < a then accum
  else range2 a (b - 1) (b :: accum);;

how to write this b < a as a pattern in match .. with ? sth like

let rec range2 a b accum = match .. with 
  | .. 

Solution

  • If you don't need to structurally pattern match anything, then match likely doesn't make sense. If/else exists for a reason, after all.

    However, you may want to learn about conditional guards on patterns. Let's say I wanted to convert an int to a type with constructors Zero, Even and Odd.

    let convert = function
      | 0 -> Zero
      | n when n % 2 = 0 -> Even
      | _ -> Odd
    

    As compared to:

    let convert n =
      if n = 0 then Zero
      else if n % 2 = 0 then Even
      else Odd
    

    Or:

    let convert = function
      | 0 -> Zero
      | n -> if n % 2 = 0 then Even else Odd