Printing result of List.Assoc.find

I try to print the resullt of an List.Assoc.find function.
But for the code:

open Core;;
let convert_int_option x:int=match x with
| Some x → 1
| None → 0;;
Printf.printf “%d” ((convert_int_option (List.Assoc.find assoc “two”)));;

The compiler is giving the error:
Printf.printf “%d” ((convert_int_option (List.Assoc.find assoc “two”)));;
Error: This expression has type
equal:(string → string → bool) → int option
but an expression was expected of type 'a option

you need to provide an “equal” function to List.Assoc.find

1 Like

The following program worked.

let assoc=[("one",1);("two",2)] in
let mytoint x = match x with
  | Some c -> c
  | None -> 0 in
let comparestrings x y=
    let x y in
    if z=0 then true
           else false in
let v=List.Assoc.find assoc ~equal:(fun x y -> comparestrings x y) "two" in
Printf.printf "%d" (mytoint v);;

The String module already has an equal function, you can just use that: List.Assoc.find ~equal:String.equal ….

Check the module documentation for that: String (base.Base.String)

There are many other helper functions as well.

Off-topic, but the same can be done more succintly, using the standard library:

let v = List.assoc_opt "two" assoc in
Printf.printf "%d" (Option.value ~default:0 v)


1 Like