Why does print_string () "hi";; not work in the context of looping through a list?

I was trying to understand what the following code does:

let rec fold_left f a list =
match list with
| [] -> a
| x::xs -> fold_left f (f a x) xs;;

when called with:

(fun () -> print_string)
["hi"; "there\n"];;

according to me the first recursive call should call:

fold_left print_string (print_string () "hi") ["there\n"])

however when I try calling that I get this error:

# print_string () "hi";;
Error: This function has type string -> unit
       It is applied to too many arguments; maybe you forgot a `;'.

what am I misunderstanding?

This still doesn’t work:

# print_string ();;
Error: This expression has type unit but an expression was expected of type

So how is the recursion I pasted at the top working then? It does work here:

# fold_left (fun () -> print_string) () ["hi"; "there\n"];;
- : unit = ()


Uh that should be

fold_left (fun () -> print_string ) ((fun () -> print_string) () "hi") ["there\n"])


1 Like

as I said in my updated question. I ran:

# fold_left (fun () -> print_string) () ["hi"; "there\n"];;
- : unit = ()

and it worked and I pasted the output of ocaml command line toplevel…so my guess is to answer no, thats not what I am doing…? but Im a beginner here so Im not sure.

Oh wait I think ur right. Let me think more carefully…

ah I see the difference now:

# print_string;;
- : string -> unit = <fun>
# (fun () -> print_string);;
- : unit -> string -> unit = <fun>

by reading the types. Thanks!