1
votes

So I have a couple of questions, as a newbie trying to learn O'Caml.

In functions, I often times see a | what does that mean? Also, why are functions some times defined as: let rec a = function Why does it specifically equal to function and then the code?

My main question however is, I was trying to write a function that would count the number of times an element exists in a list, so if I had 1, 5,5,6,9 with the target val as 5, then I'd return 2, if target val was 9, then I'd return 1, since it repeats once.

here is my attempt, please tell me what I'm doing wrong:

let rec track (x, l)= let rec helper(x,l, count)
    in counthelper
        match l with [] --> count 
    | (a::as) -> if(x = a) 
                    then helper(as,l, count+1) 
                 else count( as, l, count);;
2

2 Answers

1
votes

The match and function keywords take a list of patterns to be matched. The | symbol is used to separate the different patterns. That's why it shows up so frequently in OCaml code.

The function keyword is like an abbreviation for fun and match. It lets you define a function as a set of patterns to be matched against an argument.

Your code has let rec helper (x, l, count) in .... This isn't a proper let expression. You want something like this: let helper (x, l, count) = def in expr.

More generally your code might look like this:

let track (x, l) =
    let rec helper (x, l, count) =
        ... definition of helper ...
    in
    helper (x, l, 0)

As a side comment, you're using tuples for function parameters. It's more idiomatic in OCaml to use currying, i.e., to have separate parameters more like this:

let track x l =
    ...

This lets you do partial application (specify only some of the parameters), and also is cleaner syntactically.

Update

Your latest code doesn't return a value because it has infinite recursion.

0
votes

Usually | means pattern matching.

let rec means that function can be recursive (call itself). Tutorial.

This is my solution where some useful symbols are changed to _ symbols. Let it be an exercise for you:

let rec count y xs =
  let rec inner n = function
  | __ -> n
  | ______________ -> inner (n+1) xs
  | ____ -> inner n xs
  in 
  inner 0 xs;;

Your implementation has some issues.

  1. The most obvious one is that you are using as in pattern matching. You can't us keyword in pattern matching this way.
  2. You need to reread chapter about function declarations. It seems that you are mixing it with function invocation.
  3. You are using not curried functions. You did some in C before, don't you?
  4. You are using if when using using when is nicer. This construction is called guard.