0
votes

I start in ocaml and I would like to know how in a recursive function of type 'a list -> int ,

let rec int l =
   match l with
   | [] -> 0
   | hd::tl -> 10

the list can be flattened only if necessary for example if [0;2;3;4] just returns the int and if [[0];2; [3;4]], then do -> [0;2;3;4] and then return the int.

Thank you in advance.

1
can you represent [[0];2;[3;4]] in OCaml? why not? - coredump
sorry this is my first post, is this important to represent it in code format ? - as lack
no no, I mean you typed this list, but this is not a valid value in OCaml, because an 'a list is a list of element of some type 'a, but 2 and [2] have different types - coredump
oh yeah, this is why i want to know if i can make an if statement in function of the type or maybe just print error of type if this is not the right type - as lack

1 Answers

1
votes

You cannot store directly either a list or a number in a list, because lists must store values of the same type.

You can, however, declare a variant type (tagged union) for both kinds of values.

Here the type 'a lisr_or_val represents values that are either a value of type 'a, denoted for example (A 3), or lists of values of type 'a lisr_or_val, for example (L [(A 3); (A 5)]):

type 'a list_or_val = 
    L of 'a list_or_val list 
  | A of 'a

Then you access the leftmost value as follows:

let rec leftmost_value term = match term with
  | L ([]) -> failwith "Unexpected"
  | L (x::_) -> leftmost_value x
  | A v -> v;;

For example:

# leftmost_value (L [A 5; A 3]);;
- : int = 5