user1514567
user1514567

Reputation: 91

Calling multiple functions within another function Ocaml

I would like to know if there is anyway I can call the same function but with different arguments within another function. This is my code for the function I would like to call.

let concattoset s set = SS.add s set

With this function, I have another function that calls this function but is it possible to do something like this:

let op_change p set = concattoset (Format.asprintf "%a" processoperatorchange p) set ;concattoset (Format.asprintf "%a" processoperatorchange2 p) set ; concattoset (Format.asprintf "%a" processoperatorchange3 p) set

I know that whenever I do this, the last term is added and any other term before that is ignored. Is it possible to find out the best approach for this or if possible an alternative way of doing this?

In a similar situation within a match pattern is it possible to use the same operator. So for instance this is my match function:

let rec processoperatorchange4 fmt = function
| Zero -> Format.fprintf fmt "0"
| Pproc x -> Format.fprintf fmt "%s" x
| Procdef (p1, x) -> Format.fprintf fmt "%a(%s)"  processoperatorchange4 p1  x 
**| Par (p1, p2) -> Format.fprintf fmt "(%a | %a)" processoperatorchange4 p1 processoperatorchange4 p2 |> Format.fprintf fmt "(%a + %a)"**

Upvotes: 1

Views: 2761

Answers (2)

kne
kne

Reputation: 1418

Judging from your code, you seem to assume that SS.add s set changes the set set by adding the element s. It does not. Instead, it creates a new set with the appropriate elements. So when you do

SS.add a1 set;
SS.add a2 set;
SS.add a3 set

you create a set which contains a1 in addition to what is in set.

Then you discard that set and create a set which contains a2 in addition to what is in set (which does not contain a1 (unless it was there from the start)).

Then you discard that set as well and create a set which contains a3 in addition to what is in set (which contains neither a1 nor a2 (unless ...)). This last set is the result. All the while, set remains unchanged.

What you should do is not to discard the intermediate results, but to build upon them. Like so:

let set1 = SS.add a1 set  in
let set2 = SS.add s2 set1  in
SS.add a3 set2

or, in one go:

SS.add a3 (SS.add a2 (SS.add a1 set))

The answer by soupault shows you a different way to write the same.

Upvotes: 1

soupault
soupault

Reputation: 6510

You can use |> operator for your needs. The code above will look something like this:

let concattoset s set = SS.add s set

let op_change p set =
    concattoset (Format.asprintf "%a" processoperatorchange p) set |> 
    concattoset (Format.asprintf "%a" processoperatorchange2 p) |>  
    concattoset (Format.asprintf "%a" processoperatorchange3 p)

See also OCaml |> operator.

Upvotes: 4

Related Questions