user3447421
user3447421

Reputation: 23

OCaml doing multiple things on one line

I'm not exactly sure how to do this but lets say you have an if and else statement, and in the else clause I want to execute one statement, followed by another separate one.

For example:

let rec uniq_aux old_l new_l = match old_l with
    [] -> []
  | (h::t) ->
    if (contain h new_l) then
      uniq_aux t new_l
    else
      h::new_l ; (uniq_aux t new_l)
;;

in the last line in the code I want to add h to a new list (new_l) and keep recursing through the old list to process more info.

But I am getting an error on that line and at the line where I do: contain h new_l then

Upvotes: 0

Views: 3725

Answers (1)

Jeffrey Scofield
Jeffrey Scofield

Reputation: 66823

It appears you want the expression h :: new_l to modify new_l so it contains a new element. However, OCaml doesn't work like that. OCaml variables are immutable. (Sorry to keep repeating this, but I hope it helps to break the habit of thinking imperatively.)

Assuming I'm right about what you want the code to do, the functional programming equivalent looks roughly like this:

let new_new_l = h :: new_l in
uniq_aux t new_new_l

In other words, you can define a new variable with the value you want, and use the new variable in place of the old one.

Upvotes: 2

Related Questions