ttncrch
ttncrch

Reputation: 7253

OCaml syntax error on filter

I just begin OCaml (and functional programming) today and I'm trying to code a function that count the number of occurrences of "value" into an array (tab). I tried :

let rec count_occ tab value =
    let rec count_rec idx time = function
        | tab.length - 1 -> time
        | _ when tab.(indice) == value-> count_rec (idx + 1) (time + 1)
        | _ -> count_rec (indice + 1) time
    in
    count_rec 0 0
;;

Unfortunately, it doesn't compile because of a syntax error, and I don't find the solution.

Upvotes: 1

Views: 145

Answers (2)

ttncrch
ttncrch

Reputation: 7253

finnaly I post my final code :

let count_occ tab value =
    let rec count_rec idx time =
        if (Array.length tab) = idx then
            time
        else if (tab.(idx)) = value then
            count_rec (idx + 1) (time + 1)
        else
            count_rec (idx + 1) time
    in
    count_rec 0 0
;;

Upvotes: 1

nlucaroni
nlucaroni

Reputation: 47934

let rec count_occ tab value =

This rec above is not necessary.

    let rec count_rec idx time = function
        | tab.length - 1 -> time

You cannot match against an expression. You want to use guards like you did on the next line, or if statements to test something like this. tab.length also does not exist as tab is an array, not a record with a length field. You want Array.length tab.

Really though, you don't want the function at all. function is the same as fun x -> match x with, and would imply that count_rec has type, int -> int -> int -> int.

        | _ when tab.(indice) == value-> count_rec (idx + 1) (time + 1)

indices is not declared; lets assume you meant idx. Also, == is physical equality, you really want =.

        | _ -> count_rec (indice + 1) time
    in
    count_rec 0 0

You're off to a good start, the basics of your recursion are correct although one edge case is incorrect, but a minor issue you should be able to resolve once you have the syntactic issues fixed.

Upvotes: 3

Related Questions