I’m learning to deal with Lists and Tuples in F# and a problem came up. I have two lists: one of names and one with names,ages.
let namesToFind = [ "john", "andrea" ]
let namesAndAges = [ ("john", 10); ("andrea", 15) ]
I’m trying to create a function that will return the first age found in namesAndAges given namesToFind. Just the first.
So far I have the following code which returns the entire tuple (“john”, 10).
let findInList source target =
let itemFound = seq { for n in source do
yield target |> List.filter (fun (x,y) -> x = n) }
|> Seq.head
itemFound
I tried using fst() in the returning statement but it does not compile and gives me “This expression was expected to have type ‘a * ‘b but here has type (‘c * ‘d) list”
Thanks for any help!
There are lots of functions in the
Collections.Listmodule that can be used. Since there are nobreakor a realreturnstatement in F#, it is often better to use some search function, or write a recursive loop-function. Here is an example:The
findInListfunction is composed of two functions from theCollections.Listmodule.First we have the
List.tryFind predicate listfunction, which returns the first item for which the given predicate function returnstrue.The result is in the form of an
optiontype, which can take two values:NoneandSome(x). It is used for functions that sometimes give no useful result.The signature is:
tryFind : ('T -> bool) -> 'T list -> 'T option, where'Tis the item type, and('T -> bool)is the predicate function type.In this case it will search trough the
targetlist, looking for tuples where the first element (y) equals the variablexfrom the outer function.Then we have the
List.pick mapper listfunction, which applies themapper-function to each one, until the first result that is notNone, which is returned.This function will not return an
optionvalue, but will instead throw an exception if no item is found. There is also anoption-variant of this function namedList.tryPick.The signature is:
pick : ('T -> 'U option) -> 'T list -> 'U, where'Tis the item type,'Uis the result type, and('T -> 'U option)is the mapping function type.In this case it will go through the
source-list, looking for matches in thetargetarray (viaList.tryFind) for each one, and will stop at the first match.If you want to write the loops explicitly, here is how it could look:
(
xsandysare common ways of writing lists or sequences of items)