Ocaml IO - Printing Contents of a buffer

I am still learning ocaml and have run into an issue printing the contents of a buffer to stdout (or anything to be honest). I have tried using the buffered channels and string conversions but nothing seems to work. Even calling this (Stdio.Out_channel.output_string Stdio.stdout "lookey here";) does not print to stdout so I am not sure how to verify that my buffer ever gets updated. However, I have noticed white spaces show up instead of my desired output.

open Base

let interpret tokens =
  let tape = Array.create ~len:30000 0 in
  let outt = Buffer.create 500 in
  let rec execute acc tokens ptr =
    match tokens with
    ...
    | Dot :: rest ->
      Buffer.add_char outt (Char.unsafe_of_int tape.(ptr));
      Stdio.Out_channel.output_string Stdio.stdout "lookey here";
      execute (Dot :: acc) rest ptr
    | Comma :: rest -> 
      let ch = Stdio.In_channel.input_char Stdio.stdin in
        tape.(ptr) <-  Option.value_map ch ~default:0 ~f:Char.to_int;
      execute (Comma :: acc) rest ptr
  in
    Stdio.Out_channel.output_buffer Stdio.stdout outt;
    Stdio.Out_channel.flush Stdio.stdout;
    execute [] tokens 0

This sample uses the Base module but my prior attempts didn’t and still would not return the desired result.

Channels in OCaml are buffered. Have you tried calling flush stdout after calling output_string ?

Cheers,
Nicolas

I have. same effect. Sorry my sample didnt reflect that

What happens when you try running this program?

let () =
  let buf = Buffer.create 80 in
  Buffer.add_string buf "Hello, World\n";
  Stdio.Out_channel.output_buffer Stdio.stdout buf;
  Stdio.Out_channel.flush Stdio.stdout

Or, using only the OCaml standard library and none of this Base stuff,

let () =
  let buf = Buffer.create 80 in
  Buffer.add_string buf "Hello, World\n";
  Buffer.output_buffer Stdlib.stdout buf;
  Stdlib.flush Stdlib.stdout
6 Likes