CoderNinja
CoderNinja

Reputation: 571

Implementing multiple if statements in OCaml

So I am a little new to OCaml and I am trying to figure out a way for my function to check multiple conditions and modify a variable if any of those conditions are true

rough pseudo code would be

var list = []
if cond1 then 1::list
if cond2 then 2::list
etc

but from what I am able to tell once you enter an if statement you stay in it until it returns a value to the function. Is there a way around this limitation? Thanks for your time, tips or hints are greatly appreciated as I would love to understand the language

Upvotes: 5

Views: 33957

Answers (2)

Jeffrey Scofield
Jeffrey Scofield

Reputation: 66823

OCaml variables are immutable, you can't change their values. So you need to think of this a different way. One reasonable thing would be to have a function whose value is equal to a supplied list with something added to the front:

let f list =
    if cond1 then 1 :: list
    else if cond2 then 2 :: list
    else 3 :: list

Note that if in OCaml is an expression, i.e., it has a value. It's similar to the ?: ternary operator in languages influenced by C.

Here is an OCaml session that shows a function like this. It's just an example, this isn't a useful function:

$ ocaml
        OCaml version 4.01.0

# let f list =
      if List.length list > 3 then 1 :: list
      else if List.length list > 1 then 2 :: list
      else 3 :: list ;;
val f : int list -> int list = <fun>
# f [];;
- : int list = [3]
# f [1;2];;
- : int list = [2; 1; 2]

Update

If you want to apply the ifs all the time the code looks like this:

let f list =
    let list' = if cond1 then 1 :: list else list in
    let list'' = if cond2 then 2 :: list' else list' in
    let list''' = if cond3 then 3 :: list'' else list'' in
    list'''

You can capture the repeated pattern in its own function:

let f list =
    let cpfx cond pfx l = if cond then pfx :: l else l in
    cpfx cond3 3 (cpfx cond2 2 (cpfx cond1 1 list))

Upvotes: 10

If you want to have a sequence of if statements, each if must return unit. You can use a reference to your list to make it mutable, put semicolons after each if statement and return the referenced list at the end:

let f list =
  let list = ref list in
  if cond1 then list := 1 :: !list;
  if cond2 then list := 2 :: !list;
  [...]
  !list
;;

The given list will not be modified, there is just a new variable called list that shadows the original one within the function definition.

Upvotes: 0

Related Questions