Search code examples
lambdaf#functional-programming

List of lists, lambda and filtering results


I want to create two functions: 1) function which finds all elements less than zero in list (int list list) and then return these elements as list of (int list) type.

2) function which finds all numbers that are even on list (float list list) and then returns them as (int list).

Both of them should use at least one lambda expression (fun x -> ... ).

How to create these functions? To be honest I don't know.

let findnegative(d:int list list)=
  //maybe    List.map

let findeven (t:float list list) = 
 //something with     List.filter (fun x -> x%2.0 = 0.0)

Solution

  • I think you are looking for something like this:

    let findnegative(d:int list list) =
      d
      |> List.map (fun x -> x |> List.filter (fun y -> y < 0))
      |> List.collect id
    
    let findeven (t:float list list) = 
      t
      |> List.map (fun x -> x |> List.filter (fun y -> y % 2.0 = 0.0))
      |> List.collect id
      |> List.map int
    

    This can be simplified to:

    let findnegative =
      List.collect <| List.filter ((>)0)
    
    let findeven = 
      List.collect <| List.filter (fun x -> x % 2. = 0.) >> List.map int