I am making a function that returns the number of times a given number appears in an int list. I have a solution, but I feel it is rather elementary and could be done better (maybe with match and rec??). I also feel the styling is off, but am not too sure how to style OCaml just yet.
Here is the code:
let num_occurs (n : int) (nums : int list) : int =
let x = List.fold_left (+) 0
(List.filter (fun (x : int) ->
if x = n then true else false) nums) in
x / n ;;
So what you have looks pretty good, though I'm not sure what x / n
is intended to do. Using List.fold_left and List.filter is a good intuition for OCaml. To make this a bit cleaner, though, just use List.length! As a bonus, you can use x = n directly rather than if then else
.
let num_occurs (n : int) (nums : int list) : int =
List.length (List.filter (fun x -> x = n) nums)