tags:

views:

79

answers:

3

Suppose I have some code like this:

List.map (fun e -> if (e <> 1) then e + 1 else (*add nothing to the list*))

Is there a way to do this? If so, how?

I want to both manipulate the item if it matches some criteria and ignore it if it does not. Thus List.filter wouldn't seem to be the solution.

+6  A: 

SML has a function mapPartial which does exactly this. Sadly this function does not exist in OCaml. However you can easily define it yourself like this:

let map_partial f xs =
  let prepend_option x xs = match x with
  | None -> xs
  | Some x -> x :: xs in
  List.rev (List.fold_left (fun acc x -> prepend_option (f x) acc) [] xs)

Usage:

map_partial (fun x -> if x <> 1 then Some (x+1) else None) [0;1;2;3]

will return [1;3;4].

Or you can use filter_map from extlib as ygrek pointed out.

sepp2k
List.filter_map in extlib
ygrek
+2  A: 

Alternatively you can filter your list then apply the map on the resulted list as follows :

let map_bis predicate map_function lst =
    List.map map_function (List.filter predicate lst);;

# val map_bis : ('a -> bool) -> ('a -> 'b) -> 'a list -> 'b list = <fun>

Usage :

# map_bis (fun e -> e<>1) (fun e -> e+1) [0;1;2;3];;
- : int list = [1; 3; 4]
martani_net
+1  A: 

Both Batteries and Extlib provide an equivalent of mapPartial: their extended List module sprovide a filter_map function of the type ('a -> 'b option) -> 'a list -> 'b list, allowing the map function to select items as well.

Michael E