Question

Is it possible to pass a record or class label as a parameter to a function?

I am not sure that is the best way to describe my question / problem, perhaps it is better illustrated by this example.

Here I have hardcoded a function to filter the list where i.a is equal to v . Is it possible to make the i.a passable as well?

example code:

type myrecord =
    {
    a : int;
    b : float
    }

'

   let abclist = [{ a = 1; b = 2.}; { a = 11; b = 22.}

'

let filter1 (recordList : List<myrecord>) v =
     recordList |> List.filter (fun i -> i.a = v)

how can I make the i.a passable? so that, for example, I can call the function and filter for i.b instead?

I'm sure it's super simple (like most things in f#) but I can't beat the type error message!

Cheers,

dusiod

Was it helpful?

Solution

I am not quite sure what you are trying to do, but here are some options:

 filter1 (recordList |> List.map (fun t -> t.b)) v

or changing the declaration to

filter1 (recordList: List<myrecord>) (v:'t) (f:myrecord -> 't) = 
    recordList |> List.filter (fun i -> (f i) = v)

where f is something like fun t -> t.b

A simpler version of your existing function could be

recordList |> List.filter (function |{a=A} -> A=v)
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top