Search code examples
stringocamlhistogram

Ocaml string histogram


I'm trying to do an Histogram from String in OCaml. I'm at this state, editing a little this: create a histogram OCaml to use a String input.

How can I see the content of charFreqs, or does it works?

module S = String;;
module HT = Hashtbl;;

let histogram s =
    let charFreqs = HT.create 126 in
        S.iter (fun c ->
            let tmp =
                try HT.find charFreqs c
                with Not_found -> 0 in
            HT.replace charFreqs c (tmp+1)
        ) s;;

let str = "Lorem ipsum dolor sit amet, consectetur adipiscing elit.";;
let charFreqs = histogram str;;

Output: val charFreqs : unit = ()


Solution

  • Your histogram function returns the result of S.iter, which is unit:

    val iter : (char -> unit) -> string -> unit
    

    Try something like:

    let histogram s =
        let charFreqs = HT.create 126 in
            S.iter (fun c ->
                let tmp =
                    try HT.find charFreqs c
                    with Not_found -> 0 in
                HT.replace charFreqs c (tmp+1)
            ) s;
            charFreqs;;