move_slow_break_things
move_slow_break_things

Reputation: 847

Count the occurrence of an element in a list- OCaml

How would I go about counting the occurrence of a particular element in a list in Ocaml?

count 2 [1;2;2;2;2;3;4;5] # should return 4

I am having trouble figuring out how fold works and how I would apply it here. I tried doing:

count element list = fold (fun f ele head -> if ele = head then 1 else 0) 0 list

But this keeps returning 0 for my tests?

Upvotes: 2

Views: 6505

Answers (1)

Jeffrey Scofield
Jeffrey Scofield

Reputation: 66818

Your code is quite close. Forgive me, but I'll assume you're something of a beginner in OCaml.

In the expression fun f ele head -> ..., you're defining a function with three parameters named f, ele, and head. I suspect that you intended the f as a name for the function. But lambdas (function expressions) in OCaml don't have names (as they do in, say, JavaScript).

There is no standard function fold in OCaml. Let's assume you're working with a left fold, List.fold_left. The function to be folded takes two parameters: the first is the accumulated result from previous calls of the function, and the second is the new element from the list.

So your internal function should look more like this:

fun accum ele -> ....

The folded function returns the new accumulated result. So obviously you don't want to return just 0 or 1. You want to return the new count.

I don't want to say more, as I suspect this is part of a school assignment. I hope this helps.

(As a side comment, this question isn't about recursion. The recursion is handled for you by List.fold_left, you just need to fill in the function and initial value.)

Upvotes: 2

Related Questions