user4073801
user4073801

Reputation:

Making helper function that separates 'a list from 'a option list

I'm trying to create a helper function that can take a list like [Some 3; None; Some 5; Some 10] = [3;5;10] and output just the integers, as shown. However I'm getting a parsing error and don't know what to do about it.

apfold.ml", line 32, characters 11-12: Parse error: [opt_when_expr] expected after [patt_as_patt_opt] (in [match_case0]

The line number is referring to the line with | [Some] [int] = [int]

Here is the function thus far:

let rec difference (thelist:'a option list) : 'a list =
    match thelist with
    | [Some] [int] -> [int]
;; 

The function difference gets plugged into this:

let deoptionalize (lst:'a option list) : 'a list =
    List.filter ~f:(fun lst -> difference)
;;

Although, if there were a way to do the deoptionalize function without using a helper function, I would very much appreciate any assistance in figuring that out.

Upvotes: 0

Views: 976

Answers (3)

xyz
xyz

Reputation: 27837

Since OCaml version 4.08, this can now be done very easily by combining the List.filter_map (doc) and Fun.id (doc) functions from the Standard Library:

List.filter_map Fun.id [Some 3; None; Some 5; Some 10];;

(* returns [3; 5; 10] *)

Related question, if using the Base/Core libraries: ocaml - deoptionalize a list: is there a simpler way?

Upvotes: 0

PatJ
PatJ

Reputation: 6144

Your error comes from the [Some] [int]: this is not a valid OCaml pattern.

About using List.filter then List.map, it is quite useless to go two times through your list. You can just use a List.fold_right:

let remove_options l = List.fold_right
    (fun x result ->
     match x with
     | Some i -> i :: result
     | None -> result )
    l []

This way you go through your list once and avoid allocating an intermediate list.

Upvotes: 1

user4073801
user4073801

Reputation:

Thanks to Jeffrey Scofield and some thinking of my own, we have determined that a great way to do this would be to use List.map and List.filter to separate None from Some and then extract the int from within. The inner function can either be a helper function or an inline function; that is a style preference.

Upvotes: 0

Related Questions