let rec filtersList2fromList1 (List1:string list) (List2:string list) : string list =
let finalList = [] in
match List1 with
| s :: tl -> if List.mem s List2 = true
then finalList @ [s] else filtersList2fromList1 tl List2
| [] -> []
so that,
filtersList2fromList1 ["x";"y";"z"] ["z";"x"] would be ["x";"z"]
filtersList2fromList1 ["x";"y";"z"] ["x"] would be ["x"]
what I would like to add is, if the "if" statement is true, not only it would execute "finalList @ [s]", but also "filtersList2fromList1 tl List2" so that it will be a recursion. Without executing "filtersList2fromList1 tl List2" when it is true,
filtersList2fromList1 ["x";"y";"z"] ["z";"x"]
would only be ["x"]
, which is wrong.
How should I solve this problem?
Thank you very much
To answer your specific question, you'd either use a semi-colon or a let...in
construct. In your case, neither will do what you want however.
You should read through the documentation on the standard library, as the List
module contains everything you need to do what you want:
let filterList2fromList1 list1 list2 =
List.filter (fun x -> List.mem x list2) list1
Note that since you mentioned recursion, I'm assuming that when you wrote dolls_of
you meant filtersList2fromList1
. Also I'm assuming that List1
and List2
are supposed to be list1
and list2
, since the former would be an error.
It should also be pointed out that @
is an O(n)
operation and it is not recommended to use it to build up lists. However as Niki pointed out in the comments, your use of finalList
is pointless, so you don't actually need @
anyway.
To answer your question: You can execute two expressions after another by separating them with a ;
. However dolls_of
is a function without side effects, so executing it without doing anything with its result would make little sense.
What you actually want to do, as far as I can tell, is:
if List.mem s list2
then s :: filtersList2fromList1 tl list2
else filtersList2fromList1 tl list2
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With