0
votes

I'd like to do pattern matching with a list.

The reason is, that I have a list of flags from the Sys.argv variable and I'd like to check if all the flags are valid.

The Sys.argv list also contains the executable and a path as first two elements which I ignore

I have the following functions:

let rec compare_element_wise (user_input : string list) (valid_flags: string list) : bool =
  match user_input with
  | [] -> true
  | head::tail -> (List.mem head valid_flags) && (compare_element_wise tail valid_flags)
   (*Here print invalid flag if detected*)


let user_input_valid : bool =
  let valid_flags = ["-config"; "-module-versions"; "-json"; "-no-logging"; "-out"; "-partial"] in
  let user_input = Array.to_list Sys.argv in

  if List.length user_input > 2 then
    compare_element_wise get_user_flags valid_flags
  else true

compare_element_wise returns one boolean which indicates if all flags are valid but I would also like to print out the invalid flags, so the user knows what went wrong. (The get_user_flags is a function which return a list with flags)

I have tried to put an if else statement into the matching function but since it is recursive it would also print all preceding flags to the invalid flag.

1
Can you show the code you tried that does not work? - glennsl

1 Answers

1
votes

I am not sure I understand your issue here. Can you make the function compare_element_wise return a list of invalid flags ?

The signature becomes:

val compare_element_wise: string list -> string list -> string list

In the code of user_input_valid, you can then use the result of compare_element_wise to print out the invalid flags.

Also, note that there is a standard library package for the parsing of the command line called "Arg": https://caml.inria.fr/pub/docs/manual-ocaml/libref/Arg.html