2
\$\begingroup\$

I was going through Real World OCaml and wanted to make the program in "A Complete Program" use Async. It works now, but I'm wondering how idiomatic it is, and if I'm doing anything weird?

open Core.Std
open Async.Std

let read_and_accumulate () =
  Reader.lines (Lazy.force Reader.stdin)
  |> Pipe.filter ~f:(Fn.non String.is_empty)
  |> Pipe.map ~f:Float.of_string
  |> Pipe.fold ~init:0. ~f:(fun x y -> return (x +. y))

let () =
  ignore (read_and_accumulate ()
          >>| printf "Result is %f\n"
          >>| fun () -> exit 0);
  ignore (Scheduler.go ())

Also, I feel like I should be able to Fn.compose return (+.) for the Pipe.fold line but it doesn't work. Why not?

\$\endgroup\$
1
\$\begingroup\$

It is totally idiomatic and pretty code. My personal style is to put the pipe operators to the end, as they are, at their essence, just functional semicolons, e.g.,

let read_and_accumulate () =
  Reader.lines (Lazy.force Reader.stdin)  |> 
  Pipe.filter ~f:(Fn.non String.is_empty) |> 
  Pipe.map ~f:Float.of_string |> 
  Pipe.fold ~init:0. ~f:(fun x y -> return (x +. y))

With such approach every line starts with a word, not the punctuation that helps the readability.

What concerning the compose function, it didn't work for you because (+.) is binary (in fact it is not binary, but it is a function that returns a function). So, when you compose a return function that has type 'a -> 'b, with some function f : 'c -> 'c -> 'c, then you actually has a type ('c -> 'c) -> 'b, where ('c -> 'c) is the return type of function f. Note, the parenthesis. The ('c -> 'c) -> 'b is not equivalent to 'c -> 'c -> 'b. The first type describes a function, that takes a function and returns a value (i.e., apply-style function), and the latter type describes a function that take a value, and returns a function, that takes another value and computes the result (the curried binary function).

\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.