listfunctionocamlstrong-typingvariants

Variants and lists in Ocaml


Is it possible to define a list using variants (or something else) which would contain integers and functions simultaneously? I am particularly interested in mixing functions and some other type in a list.

Analogously is it possible to create a function which could return either a number or a function? Please if possible give code examples of both cases.


Solution

  • type my_elt = 
      | Null
      | Int of int
      | Fun1 of (int-> unit)
      | Fun2 of (int-> int)
    
    let eval a =function
      | Fun1 f -> f a;Null
      | Fun2 f -> Int (f a)
      |  _     -> Null
    
    let leval a l = List.map (fun elt -> eval a elt ) l  
    ;;
    

    Test :

    let l=[Int 2;Fun1 (Printf.printf "%d");Fun2 ((+)2) ]
    # leval 2 l;;
    2- : my_elt list = [Null; Null; Int 4]