Reputation: 37
let rec findMatches str list =
let hd :: tl = list
match list with
| [] -> []
| (s, _) as hd :: tl when s = str -> hd :: findMatches str tl
| _::tl -> findMatches str tl
This is my current function and i am stuck on how to create a new list and returning the list, I would want to test my function with this
matchs "A" [("A",5); ("BB",6); ("AA",9); ("A",0)];;
and i want it to reutrn
val it : int list = [0; 5]
so i know that i need a int list returned
Upvotes: 0
Views: 161
Reputation: 1685
This is a perfect candidate to use List.fold
from the F# library
let toMatch = "A"
let test =
[ ("A", 5)
("BB", 6)
("AA", 9)
("A", 0) ]
let findMatches toMatch items =
List.fold
(fun output item ->
if toMatch = (fst item) then
(snd item) :: output //Append if we find a match otherwise just return the same list
else
output)
[] //Set initial output to the empty list
items
findMatches toMatch test
Upvotes: 0
Reputation: 1991
It is easy to achieve your goal using a recursive inner function with an accumulator argument to collect the results one by one:
let findMatches str list =
let rec inner acc = function
| [] -> acc
| (s, n) :: tl ->
inner (if s = str then n :: acc else acc) tl
inner [] list
Upvotes: 1