Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

I want to do 2 things after a "then" statement in a "if.. then.. else" statement

Tags:

list

ocaml

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

like image 437
Mariska Avatar asked Jan 14 '11 21:01

Mariska


2 Answers

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
like image 163
Niki Yoshiuchi Avatar answered Oct 01 '22 05:10

Niki Yoshiuchi


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
like image 29
sepp2k Avatar answered Oct 01 '22 05:10

sepp2k