What is the correct way to define ambiguity function in OCaml?

I am trying to implement a simple range function in OCaml, and I was wondering how I can do this for different arity calls.

let range_aux ~start  ~stop  ~step  =
  let rec aux start stop step acc =
    match (start, stop, step, acc) with
    | (start,stop,step,acc) when start = stop -> List.rev acc
    | (start,stop,step,acc) -> aux (start + step) stop step (start :: acc) in
  aux start stop step []

let range ~start ~stop  ~step  = range_aux ~start ~stop ~step
let range ~stop  ~step  = range_aux ~start:0 ~stop ~step
let range ~stop  = range_aux ~start:0 ~stop ~step:1

This obviously does not work when the last definition wins. Is there a way to define multiple arity functions?

+4
source share
1 answer

Function overload in OCaml is generally absent. For your specific use case, you can use optional arguments:

let range ?(start=0) ?(step=1) stop = range_aux ~start ~step ~stop
let a = range 2
let b = range ~start:1 2
let c = range ~start:1 ~step:2 5

where ?(start=0)means that the named argument startis optional and its default value is 0.

, stop , , , . unit :

let range ?(start=0) ?(step=1) ~stop () = range_aux ~start ~step ~stop
let a = range ~stop:2 ()

p.s. range_aux , start > stop (stop - start) mod step ≠ 0.

+6

Source: https://habr.com/ru/post/1687972/


All Articles