Build_counts in Real World Ocaml in chapter 5. Want to print out List of tuples

I’m just trying to follow the book “Real World Ocaml” and I seem to be stuck on Chapter 5.
Here’s the code I have:

open Stdio
open Base

let build_counts () =
  In_channel.fold_lines In_channel.stdin ~init:[] ~f:(fun counts line ->
      let count =
        match List.Assoc.find ~equal:String.equal counts line with
        | None -> 0
        | Some x -> x
      in
      List.Assoc.add ~equal:String.equal counts line (count + 1))

let temp = build_counts ();
List.iter ~f:(printf "%s %i \n") temp; 

All I want to do is print temp. But I can’t seem to figure out how to do it.

The error I get is

let temp = build_counts ();
          ^^^^^^^^^^^^^^

Error: This expression has type
         (string, int) Base.List.Assoc.t = (string * int) list
       but an expression was expected of type unit
       because it is in the left-hand side of a sequence

Clearly, I don’t know what this error means or else I would have figured it out.

It’s also not clear as why deleting the “;” in let temp = build_counts (); and replacing the semicolon with an in statements gives a syntax error. (Not sure what syntax error, it just says syntax error.)

This should work:

let temp = build_counts ()
let () = List.iter ~f:(printf "%s %i \n") temp

See Syntax Error on "in" - #5 by yawaramin

1 Like