Can't run example code from the chapter on concurrent programming from RWO

I’m reading the chapter on concurrent programming in RWO but I can’t seem to run the example code.
I copy pasted it but whenever I try to build with dune build main.exe it always gives this error: Error: Unbound value Command.async_spec Hint: Did you mean basic_spec?


open Async
open Core

(* Generate a DuckDuckGo search URI from a query string *)
let query_uri query =
  let base_uri = Uri.of_string "" in
  Uri.add_query_param base_uri ("q", [query])

(* Extract the "Definition" or "Abstract" field from the DuckDuckGo results *)
let get_definition_from_json json =
  match Yojson.Safe.from_string json with
  | `Assoc kv_list ->
    let find key =
      begin match List.Assoc.find ~equal:String.equal kv_list key with
      | None | Some (`String "") -> None
      | Some s -> Some (Yojson.Safe.to_string s)
    begin match find "Abstract" with
    | Some _ as x -> x
    | None -> find "Definition"
  | _ -> None

(* Execute the DuckDuckGo search *)
let get_definition word =
  Cohttp_async.Client.get (query_uri word)
  >>= fun (_, body) ->
  Cohttp_async.Body.to_string body
  >>| fun string ->
  (word, get_definition_from_json string)

(* Print out a word/definition pair *)
let print_result (word,definition) =
  printf "%s\n%s\n\n%s\n\n"
    (String.init (String.length word) ~f:(fun _ -> '-'))
    (match definition with
    | None -> "No definition found"
    | Some def ->
      String.concat ~sep:"\n"
        (Wrapper.wrap (Wrapper.make 70) def))

let search_and_print words =
  Deferred.all ( words ~f:get_definition)
  >>| fun results ->
  List.iter results ~f:print_result

let () =
    ~summary:"Retrieve definitions from duckduckgo search engine"
      +> anon (sequence ("word" %: string))
    (fun words () -> search_and_print words)

You’re probably using an old version of async, from before Command.async was renamed to Command.async_spec.

Try opam upgrade. You can see the specific versions of the book’s dependencies in its duniverse.

Everything is updated. I even creating a new empty switch but it gives the same error. Here’s the list of packages I have installed:

# Packages matching: installed
# Name                  # Installed # Synopsis
astring                 0.8.3       Alternative String module for OCaml
async                   v0.13.0     Monadic concurrency library
async_kernel            v0.13.0     Monadic concurrency library
async_rpc_kernel        v0.13.0     Platform-independent core of Async RPC library
async_unix              v0.13.0     Monadic concurrency library
base                    v0.13.1     Full standard library replacement for OCaml
base-bigarray           base
base-bytes              base        Bytes library distributed with the OCaml compiler
base-threads            base
base-unix               base
base64                  3.4.0       Base64 encoding for OCaml
base_bigstring          v0.13.0     String type based on [Bigarray], for use in I/O and C-bindings
base_quickcheck         v0.13.0     Randomized testing framework, designed for compatibility with Base
bin_prot                v0.13.0     A binary protocol generator
biniou                  1.2.1       Binary data format designed for speed, safety, ease of use and backward compatibility as protocols evolve
cohttp                  2.5.1       An OCaml library for HTTP clients and servers
cohttp-async            2.5.1       CoHTTP implementation for the Async concurrency library
conduit                 2.1.0       A network connection establishment library
conduit-async           2.1.0       A network connection establishment library for Async
conf-m4                 1           Virtual package relying on m4
core                    v0.13.0     Industrial strength alternative to OCaml's standard library
core_kernel             v0.13.1     Industrial strength alternative to OCaml's standard library
cppo                    1.6.6       Code preprocessor like cpp for OCaml
domain-name             0.3.0       RFC 1035 Internet domain names
dune                    2.5.1       Fast, portable, and opinionated build system
dune-configurator       2.5.1       Helper library for gathering system configuration
dune-private-libs       2.5.1       Private libraries of Dune
easy-format             1.3.2       High-level and functional interface to the Format module of the OCaml standard library
fieldslib               v0.13.0     Syntax extension to define first class values representing record fields, to get and set record fields, iterate and fold over all fields of a record and create new record values
fmt                     0.8.8       OCaml Format pretty-printer combinators
ipaddr                  4.0.0       A library for manipulation of IP (and MAC) address representations
ipaddr-sexp             4.0.0       A library for manipulation of IP address representations usnig sexp
jane-street-headers     v0.13.0     Jane Street C header files
jsonm                   1.0.1       Non-blocking streaming JSON codec for OCaml
jst-config              v0.13.0     Compile-time configuration for Jane Street libraries
logs                    0.7.0       Logging infrastructure for OCaml
macaddr                 4.0.0       A library for manipulation of MAC address representations
magic-mime              1.1.2       Map filenames to common MIME types
num                     1.3         The legacy Num library for arbitrary-precision integer and rational arithmetic
ocaml                   4.09.0      The OCaml compiler (virtual package)
ocaml-base-compiler     4.09.0      Official release 4.09.0
ocaml-compiler-libs     v0.12.1     OCaml compiler libraries repackaged
ocaml-config            1           OCaml Switch Configuration
ocaml-migrate-parsetree 1.7.2       Convert OCaml parsetrees between different versions
ocamlbuild              0.14.0      OCamlbuild is a build system with builtin rules to easily build most OCaml projects.
ocamlfind               1.8.1       A library manager for OCaml
octavius                1.2.2       Ocamldoc comment syntax parser
parsexp                 v0.13.0     S-expression parsing library
ppx_assert              v0.13.0     Assert-like extension nodes that raise useful errors on failure
ppx_base                v0.13.0     Base set of ppx rewriters
ppx_bench               v0.13.0     Syntax extension for writing in-line benchmarks in ocaml code
ppx_bin_prot            v0.13.0     Generation of bin_prot readers and writers from types
ppx_cold                v0.13.0     Expands [@cold] into [@inline never][@specialise never][@local never]
ppx_compare             v0.13.0     Generation of comparison functions from types
ppx_custom_printf       v0.13.0     Printf-style format-strings for user-defined string conversion
ppx_derivers            1.2.1       Shared [@@deriving] plugin registry
ppx_enumerate           v0.13.0     Generate a list containing all values of a finite type
ppx_expect              v0.13.0     Cram like framework for OCaml
ppx_fail                v0.13.0     Add location to calls to failwiths
ppx_fields_conv         v0.13.0     Generation of accessor and iteration functions for ocaml records
ppx_hash                v0.13.0     A ppx rewriter that generates hash functions from type expressions and definitions
ppx_here                v0.13.0     Expands [%here] into its location
ppx_inline_test         v0.13.1     Syntax extension for writing in-line tests in ocaml code
ppx_jane                v0.13.0     Standard Jane Street ppx rewriters
ppx_js_style            v0.13.0     Code style checker for Jane Street Packages
ppx_let                 v0.13.0     Monadic let-bindings
ppx_module_timer        v0.13.0     Ppx rewriter that records top-level module startup times
ppx_optcomp             v0.13.0     Optional compilation for OCaml
ppx_optional            v0.13.0     Pattern matching on flat options
ppx_pipebang            v0.13.0     A ppx rewriter that inlines reverse application operators `|>` and `|!`
ppx_sexp_conv           v0.13.0     [@@deriving] plugin to generate S-expression conversion functions
ppx_sexp_message        v0.13.0     A ppx rewriter for easy construction of s-expressions
ppx_sexp_value          v0.13.0     A ppx rewriter that simplifies building s-expressions from ocaml values
ppx_stable              v0.13.0     Stable types conversions generator
ppx_typerep_conv        v0.13.0     Generation of runtime types from type declarations
ppx_variants_conv       v0.13.0     Generation of accessor and iteration functions for ocaml variant types
ppxlib                  0.13.0      Base library and tools for ppx rewriters
protocol_version_header v0.13.0     Protocol versioning
re                      1.9.0       RE is a regular expression library for OCaml
result                  1.5         Compatibility Result module
seq                     base        Compatibility package for OCaml's standard iterator type starting from 4.07.
sexplib                 v0.13.0     Library for serializing OCaml values to and from S-expressions
sexplib0                v0.13.0     Library containing the definition of S-expressions and some base converters
spawn                   v0.13.0     Spawning sub-processes
splittable_random       v0.13.0     PRNG that can be split into independent streams
stdio                   v0.13.0     Standard IO library for OCaml
stdlib-shims            0.1.0       Backport some of the new stdlib features to older compiler
stringext               1.6.0       Extra string functions for OCaml
textutils               v0.13.0     Text output utilities
textwrap                0.2         Text wrapping and filling library
time_now                v0.13.0     Reports the current time
topkg                   1.0.1       The transitory OCaml software packager
typerep                 v0.13.0     Typerep is a library for runtime types
uchar                   0.0.2       Compatibility library for OCaml's Uchar module
uri                     3.1.0       An RFC3986 URI/URL parsing library
uri-sexp                3.1.0       An RFC3986 URI/URL parsing library
uutf                    1.0.2       Non-blocking streaming Unicode codec for OCaml
variantslib             v0.13.0     Part of Jane Street's Core library
yojson                  1.7.0       Yojson is an optimized parsing and printing library for the JSON format

Ah, this example in RWO isn’t being tested against the newest API yet, and so it’s out-of-date. Sorry for the confusion.

Try switching out Command.async_spec for Async_command.async_spec. This builds correctly for me on the v0.13 set of JS packages.

1 Like

Yeah, that works. Everything is so hard when you’re a noob :sweat_smile:

Thanks a lot!

1 Like