Baily
Baily

Reputation: 1380

OCaml return value in if statement nested in loop

I am trying to return a value if something occurs when iterating through a list. Is it possible to return a string if X happens when iterating through the list, otherwise return another string if it never happens?

let f elem =
  if not String.contains str elem then "false" in
List.iter f alphlist;

"true";

This is not working in my implemented method sadly.

Upvotes: 0

Views: 836

Answers (1)

Jeffrey Scofield
Jeffrey Scofield

Reputation: 66808

OCaml is a functional language, so you pretty much need to concentrate on the values returned by functions. There are ways to return different values in exceptional cases, but (IMHO) the best way to learn is to start just with ordinary old nested function calls.

List.iter always returns the same value: (), which is known as unit.

For this reason, the expression List.iter f alphlist will also always return () no matter what f does.

There is another kind of list-handling function that works by maintaining a value across all the calls and returning that value at the end. It's called a fold.

So, if you want to compute some value that's a kind of summary of what it saw in all of the string lists in alphlist, you should probably be using a fold, say List.fold_left.

Here is a function any_has_7 that determines whether any one of the specified lists contains the integer 7:

let any_has_7 lists =
    let has_7 sofar list =
        sofar || List.mem 7 list
    in
    List.fold_left has_7 false lists

Here's how it looks when you run it:

# any_has_7 [[1;2]; [3;4]];;
- : bool = false
# any_has_7 [[1;2]; [5;7]; [8;9]];;
- : bool = true

In other words, this function does something a lot like what you're asking for. It returns true when one or more of the lists contains a certain value, and false when none of them contains the value.

I hope this helps.

Upvotes: 1

Related Questions