{"title":"Joe Thomas - OCaml","link":[{"@attributes":{"href":"https:\/\/jsthomas.github.io\/","rel":"alternate"}},{"@attributes":{"href":"https:\/\/jsthomas.github.io\/feeds\/ocaml.atom.xml","rel":"self"}}],"id":"https:\/\/jsthomas.github.io\/","updated":"2021-07-23T00:00:00-04:00","entry":[{"title":"How to send emails from Dream","link":{"@attributes":{"href":"https:\/\/jsthomas.github.io\/ocaml-email.html","rel":"alternate"}},"published":"2021-07-23T00:00:00-04:00","updated":"2021-07-23T00:00:00-04:00","author":{"name":"Joe Thomas"},"id":"tag:jsthomas.github.io,2021-07-23:\/ocaml-email.html","summary":"<p>How to build an email queue system for a Dream web server.<\/p>","content":"<p>I recently <a href=\"https:\/\/github.com\/aantron\/dream\/issues\/138\">learned<\/a> the\nOCaml ecosystem has most of the libraries needed to build email\nfeatures, but I wasn't able to find an example that brings all of\nthose pieces together. I wanted a simple example I could easily adapt\nto build common account verification and password recovery workflows\nin the Dream web framework. This post is my attempt to solve that\nproblem and explain what I learned in the process. The accompanying\ncode can be found\n<a href=\"https:\/\/github.com\/jsthomas\/dream-email-example\">here<\/a>.<\/p>\n<h2>Defining the problem<\/h2>\n<p>As an application developer, my main concerns when\nsending mail are:<\/p>\n<ol>\n<li>Trying to ensure the address I'm sending to is valid.<\/li>\n<li>Handling the email synthesis process asynchronously, so it doesn't\n   block the web server from handling requests quickly.<\/li>\n<li>Transmitting the email content (SMTP or a REST API call)<\/li>\n<li>Monitoring that the applications messages aren't getting\n   blocked\/dropped for some reason.<\/li>\n<\/ol>\n<p>To test how easily I could satisfy these requirements, I built a web\napp that lets the user send an arbitary email.<\/p>\n<p><img alt=\"A screenshot of the email form.\" src=\"https:\/\/jsthomas.github.io\/images\/ocaml-email\/screenshot.png\"><\/p>\n<p>The app has two parts:<\/p>\n<ul>\n<li>A server process responsible for showing the form above and\n  validating user inputs.<\/li>\n<li>A \"worker\" process responsible for sending mail. The worker gets its\n  tasks from a queue populated by the server.<\/li>\n<\/ul>\n<h2>Validating Email Addresses<\/h2>\n<p>I decided to utilize the library\n<a href=\"https:\/\/github.com\/dinosaure\/emile\"><code>emile<\/code><\/a> for address\nvalidation. An email address might be invalid for reasons outside of\nthe application's control (like the domain going way), but <code>emile<\/code> at\nleast provides a way to check a given string conforms to 5(!) RFCs\nrelevant to parsing email addresses. Check out the\n<a href=\"https:\/\/github.com\/dinosaure\/emile\/blob\/master\/test\/test.ml#L34\">tests<\/a>\nto see the impressive diversity of valid email addresses on the web.<\/p>\n<p>The library provides several different predicates for checking\naddresses. I utilized <code>Emile.of_string<\/code>, which generates a simple\nresult type, like this:<\/p>\n<div class=\"highlight\"><pre><span><\/span><code><span class=\"k\">let<\/span> <span class=\"n\">form_post<\/span> <span class=\"n\">request<\/span> <span class=\"o\">=<\/span>\n  <span class=\"k\">match<\/span><span class=\"o\">%<\/span><span class=\"n\">lwt<\/span> <span class=\"nn\">Dream<\/span><span class=\"p\">.<\/span><span class=\"n\">form<\/span> <span class=\"n\">request<\/span> <span class=\"k\">with<\/span>\n    <span class=\"o\">|<\/span> <span class=\"o\">`<\/span><span class=\"nc\">Ok<\/span> <span class=\"o\">[<\/span><span class=\"s2\">&quot;address&quot;<\/span><span class=\"o\">,<\/span> <span class=\"n\">address<\/span><span class=\"o\">;<\/span> <span class=\"s2\">&quot;message&quot;<\/span><span class=\"o\">,<\/span> <span class=\"n\">message<\/span><span class=\"o\">;<\/span> <span class=\"s2\">&quot;subject&quot;<\/span><span class=\"o\">,<\/span> <span class=\"n\">subject<\/span> <span class=\"o\">]<\/span> <span class=\"o\">-&gt;<\/span>\n      <span class=\"k\">let<\/span> <span class=\"n\">parse<\/span> <span class=\"o\">=<\/span> <span class=\"nn\">Emile<\/span><span class=\"p\">.<\/span><span class=\"n\">of_string<\/span> <span class=\"n\">address<\/span> <span class=\"k\">in<\/span>\n      <span class=\"k\">let<\/span> <span class=\"n\">alert<\/span> <span class=\"o\">=<\/span> <span class=\"k\">match<\/span> <span class=\"n\">parse<\/span> <span class=\"k\">with<\/span>\n        <span class=\"o\">|<\/span> <span class=\"nc\">Ok<\/span> <span class=\"o\">_<\/span> <span class=\"o\">-&gt;<\/span> <span class=\"nn\">Printf<\/span><span class=\"p\">.<\/span><span class=\"n\">sprintf<\/span> <span class=\"s2\">&quot;Sent an email to %s.&quot;<\/span> <span class=\"n\">address<\/span>\n        <span class=\"o\">|<\/span> <span class=\"nc\">Error<\/span> <span class=\"o\">_<\/span> <span class=\"o\">-&gt;<\/span> <span class=\"nn\">Printf<\/span><span class=\"p\">.<\/span><span class=\"n\">sprintf<\/span> <span class=\"s2\">&quot;%s is not a valid email address.&quot;<\/span> <span class=\"n\">address<\/span>\n      <span class=\"k\">in<\/span>\n      <span class=\"k\">let<\/span> <span class=\"n\">queue_req<\/span> <span class=\"o\">=<\/span> <span class=\"k\">match<\/span> <span class=\"n\">parse<\/span> <span class=\"k\">with<\/span>\n        <span class=\"o\">|<\/span> <span class=\"nc\">Ok<\/span> <span class=\"o\">_<\/span> <span class=\"o\">-&gt;<\/span> <span class=\"n\">queue_email<\/span> <span class=\"n\">address<\/span> <span class=\"n\">subject<\/span> <span class=\"n\">message<\/span>\n        <span class=\"o\">|<\/span> <span class=\"nc\">Error<\/span> <span class=\"o\">_<\/span> <span class=\"o\">-&gt;<\/span> <span class=\"nn\">Lwt<\/span><span class=\"p\">.<\/span><span class=\"n\">return_unit<\/span>\n    <span class=\"k\">in<\/span>\n    <span class=\"n\">queue_req<\/span> <span class=\"o\">&gt;&gt;=<\/span> <span class=\"o\">(<\/span><span class=\"k\">fun<\/span> <span class=\"o\">_<\/span> <span class=\"o\">-&gt;<\/span>\n        <span class=\"nn\">Dream<\/span><span class=\"p\">.<\/span><span class=\"n\">html<\/span> <span class=\"o\">(<\/span><span class=\"nn\">Template<\/span><span class=\"p\">.<\/span><span class=\"n\">show_form<\/span> <span class=\"o\">~<\/span><span class=\"n\">alert<\/span> <span class=\"n\">request<\/span><span class=\"o\">))<\/span>\n    <span class=\"o\">|<\/span> <span class=\"o\">_<\/span> <span class=\"o\">-&gt;<\/span> <span class=\"nn\">Dream<\/span><span class=\"p\">.<\/span><span class=\"n\">empty<\/span> <span class=\"o\">`<\/span><span class=\"nc\">Bad_Request<\/span>\n<\/code><\/pre><\/div>\n\n<p>This way, if a user provides an invalid address, the form displays a simple\nwarning message and won't queue any email tasks.<\/p>\n<h2>Queuing Tasks with RabbitMQ<\/h2>\n<p>The second issue I needed to address is handling the email send\nprocess with a background worker (<code>queue_email<\/code> in the code excerpt\nabove). Sending an email can be a slow process, especially if you need\nto make additional database queries or render images to produce a\ncustomized email. That shouldn't block the web server from quickly\nresponding to the user's requests. Instead, the server should record\nthe email task in a <em>queue<\/em>, to be handled by a background worker that\nisn't as sensitive to latency.<\/p>\n<p>There are several different technologies that can be used to solve\nthis problem, for example <a href=\"https:\/\/www.rabbitmq.com\/\">RabbitMQ<\/a>,\n<a href=\"https:\/\/redislabs.com\/ebook\/part-2-core-concepts\/chapter-6-application-components-in-redis\/6-4-task-queues\/6-4-1-first-in-first-out-queues\/\">Redis<\/a>\nand <a href=\"https:\/\/aws.amazon.com\/sqs\/\">SQS<\/a>. I decided to use RabbitMQ\nbecause I didn't want to tie my implementation to one cloud provider\nand RabbitMQ is supported by\n<a href=\"https:\/\/github.com\/andersfugmann\/amqp-client\">amqp-client<\/a> on\nOPAM. This isn't the only way to go: for Redis and SQS, you might have\nsuccess with the packages\n<a href=\"https:\/\/opam.ocaml.org\/packages\/redis\/\">redis<\/a> or\n<a href=\"https:\/\/opam.ocaml.org\/packages\/aws-sqs\/\">aws-sqs<\/a>, respectively.<\/p>\n<p>The worker and server process share a common function for establishing\na connection to RabbitMQ:<\/p>\n<div class=\"highlight\"><pre><span><\/span><code><span class=\"k\">let<\/span> <span class=\"n\">rabbit_connection<\/span> <span class=\"bp\">()<\/span> <span class=\"o\">=<\/span>\n  <span class=\"k\">let<\/span><span class=\"o\">%<\/span><span class=\"n\">lwt<\/span> <span class=\"n\">connection<\/span> <span class=\"o\">=<\/span> <span class=\"nn\">Connection<\/span><span class=\"p\">.<\/span><span class=\"n\">connect<\/span> <span class=\"o\">~<\/span><span class=\"n\">id<\/span><span class=\"o\">:<\/span><span class=\"s2\">&quot;dream&quot;<\/span> <span class=\"s2\">&quot;localhost&quot;<\/span> <span class=\"k\">in<\/span>\n  <span class=\"k\">let<\/span><span class=\"o\">%<\/span><span class=\"n\">lwt<\/span> <span class=\"n\">channel<\/span> <span class=\"o\">=<\/span> <span class=\"nn\">Connection<\/span><span class=\"p\">.<\/span><span class=\"n\">open_channel<\/span> <span class=\"o\">~<\/span><span class=\"n\">id<\/span><span class=\"o\">:<\/span><span class=\"s2\">&quot;email&quot;<\/span> <span class=\"nn\">Channel<\/span><span class=\"p\">.<\/span><span class=\"n\">no_confirm<\/span> <span class=\"n\">connection<\/span> <span class=\"k\">in<\/span>\n  <span class=\"k\">let<\/span><span class=\"o\">%<\/span><span class=\"n\">lwt<\/span> <span class=\"n\">queue<\/span> <span class=\"o\">=<\/span> <span class=\"nn\">Queue<\/span><span class=\"p\">.<\/span><span class=\"n\">declare<\/span> <span class=\"n\">channel<\/span> <span class=\"o\">~<\/span><span class=\"n\">arguments<\/span><span class=\"o\">:[<\/span><span class=\"nn\">Rpc<\/span><span class=\"p\">.<\/span><span class=\"nn\">Server<\/span><span class=\"p\">.<\/span><span class=\"n\">queue_argument<\/span><span class=\"o\">]<\/span> <span class=\"s2\">&quot;email&quot;<\/span> <span class=\"k\">in<\/span>\n  <span class=\"nn\">Lwt<\/span><span class=\"p\">.<\/span><span class=\"n\">return<\/span> <span class=\"o\">(<\/span><span class=\"n\">channel<\/span><span class=\"o\">,<\/span> <span class=\"n\">queue<\/span><span class=\"o\">)<\/span>\n<\/code><\/pre><\/div>\n\n<p>I was initially little confused about why I needed a \"channel\" when I\nalready had a connection to the broker. Both the worker and the server\nconnect to the RabbitMQ Broker via TCP. It's common for clients to\nneed several connections to the broker, but it's costly to have many\nTCP connections. RabbitMQ lets us avoid this cost with channels, which\nare like \"lightweight connections that share a single TCP\nconnection\", according to these <a href=\"https:\/\/www.rabbitmq.com\/channels.html\">docs<\/a>.<\/p>\n<p>I created this function to submit messages to the queue:<\/p>\n<div class=\"highlight\"><pre><span><\/span><code><span class=\"k\">type<\/span> <span class=\"n\">email<\/span> <span class=\"o\">=<\/span> <span class=\"o\">{<\/span>\n  <span class=\"n\">address<\/span><span class=\"o\">:<\/span> <span class=\"kt\">string<\/span><span class=\"o\">;<\/span>\n  <span class=\"n\">subject<\/span><span class=\"o\">:<\/span> <span class=\"kt\">string<\/span><span class=\"o\">;<\/span>\n  <span class=\"n\">text<\/span><span class=\"o\">:<\/span> <span class=\"kt\">string<\/span><span class=\"o\">;<\/span>\n<span class=\"o\">}<\/span> <span class=\"o\">[@@<\/span><span class=\"n\">deriving<\/span> <span class=\"n\">yojson<\/span><span class=\"o\">]<\/span>\n\n<span class=\"k\">let<\/span> <span class=\"n\">queue_email<\/span> <span class=\"n\">address<\/span> <span class=\"n\">subject<\/span> <span class=\"n\">text<\/span> <span class=\"o\">=<\/span>\n  <span class=\"k\">let<\/span> <span class=\"n\">email<\/span> <span class=\"o\">=<\/span> <span class=\"o\">{<\/span><span class=\"n\">address<\/span><span class=\"o\">;<\/span> <span class=\"n\">subject<\/span><span class=\"o\">;<\/span> <span class=\"n\">text<\/span><span class=\"o\">}<\/span> <span class=\"k\">in<\/span>\n  <span class=\"k\">let<\/span> <span class=\"n\">text<\/span> <span class=\"o\">=<\/span> <span class=\"n\">email<\/span> <span class=\"o\">|&gt;<\/span> <span class=\"n\">yojson_of_email<\/span> <span class=\"o\">|&gt;<\/span> <span class=\"nn\">Yojson<\/span><span class=\"p\">.<\/span><span class=\"nn\">Safe<\/span><span class=\"p\">.<\/span><span class=\"n\">to_string<\/span> <span class=\"k\">in<\/span>\n  <span class=\"k\">let<\/span><span class=\"o\">%<\/span><span class=\"n\">lwt<\/span> <span class=\"n\">channel<\/span><span class=\"o\">,<\/span> <span class=\"n\">queue<\/span> <span class=\"o\">=<\/span> <span class=\"n\">rabbit_connection<\/span> <span class=\"bp\">()<\/span> <span class=\"k\">in<\/span>\n  <span class=\"k\">let<\/span><span class=\"o\">%<\/span><span class=\"n\">lwt<\/span> <span class=\"o\">_<\/span> <span class=\"o\">=<\/span> <span class=\"nn\">Queue<\/span><span class=\"p\">.<\/span><span class=\"n\">publish<\/span> <span class=\"n\">channel<\/span> <span class=\"n\">queue<\/span> <span class=\"o\">(<\/span><span class=\"nn\">Message<\/span><span class=\"p\">.<\/span><span class=\"n\">make<\/span> <span class=\"n\">text<\/span><span class=\"o\">)<\/span> <span class=\"k\">in<\/span>\n  <span class=\"nn\">Lwt<\/span><span class=\"p\">.<\/span><span class=\"n\">return_unit<\/span>\n<\/code><\/pre><\/div>\n\n<p>Here the server writes the address, subject, and text into a record\ntype that can be serialized to JSON before being pushed into the queue.<\/p>\n<p>The worker process, <code>queue_worker<\/code>, is fairly simple to define:<\/p>\n<div class=\"highlight\"><pre><span><\/span><code><span class=\"k\">let<\/span> <span class=\"n\">handle_message<\/span> <span class=\"o\">(<\/span><span class=\"n\">m<\/span><span class=\"o\">:<\/span> <span class=\"nn\">Message<\/span><span class=\"p\">.<\/span><span class=\"n\">t<\/span><span class=\"o\">)<\/span> <span class=\"o\">=<\/span>\n  <span class=\"k\">let<\/span> <span class=\"n\">text<\/span> <span class=\"o\">=<\/span> <span class=\"n\">snd<\/span> <span class=\"n\">m<\/span><span class=\"o\">.<\/span><span class=\"n\">message<\/span> <span class=\"k\">in<\/span>\n  <span class=\"k\">let<\/span> <span class=\"n\">email<\/span> <span class=\"o\">=<\/span>\n    <span class=\"k\">try<\/span>\n      <span class=\"nc\">Some<\/span> <span class=\"o\">(<\/span><span class=\"n\">text<\/span> <span class=\"o\">|&gt;<\/span> <span class=\"nn\">Yojson<\/span><span class=\"p\">.<\/span><span class=\"nn\">Safe<\/span><span class=\"p\">.<\/span><span class=\"n\">from_string<\/span> <span class=\"o\">|&gt;<\/span> <span class=\"n\">email_of_yojson<\/span><span class=\"o\">)<\/span>\n    <span class=\"k\">with<\/span> <span class=\"o\">_<\/span> <span class=\"o\">-&gt;<\/span>\n      <span class=\"nn\">Printf<\/span><span class=\"p\">.<\/span><span class=\"n\">printf<\/span> <span class=\"s2\">&quot;Received invalid email record from RabbitMQ: %s&quot;<\/span> <span class=\"n\">text<\/span><span class=\"o\">;<\/span>\n      <span class=\"nc\">None<\/span>\n  <span class=\"k\">in<\/span>\n  <span class=\"k\">match<\/span> <span class=\"n\">email<\/span> <span class=\"k\">with<\/span>\n  <span class=\"o\">|<\/span> <span class=\"nc\">Some<\/span> <span class=\"n\">e<\/span> <span class=\"o\">-&gt;<\/span> <span class=\"n\">send_email<\/span> <span class=\"n\">e<\/span>\n  <span class=\"o\">|<\/span> <span class=\"nc\">None<\/span> <span class=\"o\">-&gt;<\/span> <span class=\"nn\">Lwt<\/span><span class=\"p\">.<\/span><span class=\"n\">return_unit<\/span>\n\n\n<span class=\"k\">let<\/span> <span class=\"n\">queue_worker<\/span> <span class=\"bp\">()<\/span> <span class=\"o\">=<\/span>\n  <span class=\"nn\">Printf<\/span><span class=\"p\">.<\/span><span class=\"n\">printf<\/span> <span class=\"s2\">&quot;Starting Queue Worker<\/span><span class=\"se\">\\n<\/span><span class=\"s2\">&quot;<\/span><span class=\"o\">;<\/span>\n  <span class=\"k\">let<\/span><span class=\"o\">%<\/span><span class=\"n\">lwt<\/span> <span class=\"n\">channel<\/span><span class=\"o\">,<\/span> <span class=\"n\">queue<\/span> <span class=\"o\">=<\/span> <span class=\"n\">rabbit_connection<\/span> <span class=\"bp\">()<\/span> <span class=\"k\">in<\/span>\n  <span class=\"k\">let<\/span> <span class=\"k\">rec<\/span> <span class=\"n\">handle<\/span> <span class=\"bp\">()<\/span> <span class=\"o\">=<\/span>\n    <span class=\"nn\">Queue<\/span><span class=\"p\">.<\/span><span class=\"n\">get<\/span> <span class=\"o\">~<\/span><span class=\"n\">no_ack<\/span><span class=\"o\">:<\/span><span class=\"bp\">true<\/span> <span class=\"n\">channel<\/span> <span class=\"n\">queue<\/span> <span class=\"o\">&gt;&gt;=<\/span> <span class=\"k\">fun<\/span> <span class=\"n\">message<\/span> <span class=\"o\">-&gt;<\/span>\n    <span class=\"k\">let<\/span> <span class=\"n\">task<\/span> <span class=\"o\">=<\/span> <span class=\"k\">match<\/span> <span class=\"n\">message<\/span> <span class=\"k\">with<\/span>\n      <span class=\"o\">|<\/span> <span class=\"nc\">Some<\/span> <span class=\"n\">m<\/span> <span class=\"o\">-&gt;<\/span> <span class=\"n\">flush<\/span> <span class=\"n\">stdout<\/span><span class=\"o\">;<\/span> <span class=\"n\">handle_message<\/span> <span class=\"n\">m<\/span>\n      <span class=\"o\">|<\/span> <span class=\"o\">_<\/span> <span class=\"o\">-&gt;<\/span> <span class=\"nn\">Printf<\/span><span class=\"p\">.<\/span><span class=\"n\">printf<\/span> <span class=\"s2\">&quot;No new tasks, waiting.<\/span><span class=\"se\">\\n<\/span><span class=\"s2\">&quot;<\/span><span class=\"o\">;<\/span> <span class=\"n\">flush<\/span> <span class=\"n\">stdout<\/span><span class=\"o\">;<\/span> <span class=\"nn\">Lwt_unix<\/span><span class=\"p\">.<\/span><span class=\"n\">sleep<\/span> <span class=\"mi\">5<\/span><span class=\"o\">.<\/span>\n    <span class=\"k\">in<\/span>\n    <span class=\"n\">task<\/span> <span class=\"o\">&gt;&gt;=<\/span> <span class=\"n\">handle<\/span>\n  <span class=\"k\">in<\/span>\n  <span class=\"n\">handle<\/span> <span class=\"bp\">()<\/span>\n<\/code><\/pre><\/div>\n\n<p>The worker consists of an infinite loop. When the worker wakes and\nfinds tasks in the queue, it uses <code>yojson<\/code> to deserialize the\nmessages and passes them to <code>send_email<\/code>. If no work is available,\nthe worker just sleeps for 5 seconds.<\/p>\n<h2>Sending Email with <code>cohttp<\/code> and Mailgun<\/h2>\n<p>In order to send mail, I set up a trial\n<a href=\"https:\/\/documentation.mailgun.com\/en\/latest\/quickstart-sending.html#send-via-smtp\">Mailgun<\/a>\naccount. I selected this provider for several reasons:<\/p>\n<ul>\n<li>Mailgun has a generous free tier (5000 emails).<\/li>\n<li>A new account also comes with a \"sandbox\" domain, so I didn't have\n  to deal with registering a domain.<\/li>\n<li>Mailgun supports both a REST API and SMTP, allowing me to try\n  different integrations.<\/li>\n<li>Mailgun provides dashboards for tracking messages sent over time as\n  well as emails that were rejected (bounced, marked as spam, etc.).<\/li>\n<\/ul>\n<p>Mailgun's API allowed me to send an email by sending a POST with an API key and form\ndata, like this:<\/p>\n<div class=\"highlight\"><pre><span><\/span><code><span class=\"k\">let<\/span> <span class=\"n\">send_email<\/span> <span class=\"o\">(<\/span><span class=\"n\">e<\/span><span class=\"o\">:<\/span> <span class=\"n\">email<\/span><span class=\"o\">)<\/span> <span class=\"o\">=<\/span>\n   <span class=\"k\">let<\/span> <span class=\"k\">open<\/span> <span class=\"nc\">Cohttp<\/span> <span class=\"k\">in<\/span>\n   <span class=\"k\">let<\/span> <span class=\"k\">open<\/span> <span class=\"nc\">Cohttp_lwt_unix<\/span> <span class=\"k\">in<\/span>\n\n   <span class=\"k\">let<\/span> <span class=\"n\">api_key<\/span> <span class=\"o\">=<\/span> <span class=\"nn\">Sys<\/span><span class=\"p\">.<\/span><span class=\"n\">getenv<\/span> <span class=\"s2\">&quot;MAILGUN_API_KEY&quot;<\/span> <span class=\"k\">in<\/span>\n   <span class=\"k\">let<\/span> <span class=\"n\">sender<\/span> <span class=\"o\">=<\/span> <span class=\"nn\">Sys<\/span><span class=\"p\">.<\/span><span class=\"n\">getenv<\/span> <span class=\"s2\">&quot;MAILGUN_SEND_ADDRESS&quot;<\/span> <span class=\"k\">in<\/span>\n   <span class=\"k\">let<\/span> <span class=\"n\">api_base<\/span> <span class=\"o\">=<\/span> <span class=\"nn\">Sys<\/span><span class=\"p\">.<\/span><span class=\"n\">getenv<\/span> <span class=\"s2\">&quot;MAILGUN_API_BASE&quot;<\/span> <span class=\"k\">in<\/span>\n\n   <span class=\"k\">let<\/span> <span class=\"n\">params<\/span> <span class=\"o\">=<\/span> <span class=\"o\">[<\/span>\n     <span class=\"o\">(<\/span><span class=\"s2\">&quot;from&quot;<\/span><span class=\"o\">,<\/span> <span class=\"o\">[<\/span><span class=\"n\">sender<\/span><span class=\"o\">]);<\/span>\n     <span class=\"o\">(<\/span><span class=\"s2\">&quot;to&quot;<\/span><span class=\"o\">,<\/span> <span class=\"o\">[<\/span><span class=\"n\">e<\/span><span class=\"o\">.<\/span><span class=\"n\">address<\/span><span class=\"o\">]);<\/span>\n     <span class=\"o\">(<\/span><span class=\"s2\">&quot;subject&quot;<\/span><span class=\"o\">,<\/span> <span class=\"o\">[<\/span><span class=\"n\">e<\/span><span class=\"o\">.<\/span><span class=\"n\">subject<\/span><span class=\"o\">]);<\/span>\n     <span class=\"o\">(<\/span><span class=\"s2\">&quot;text&quot;<\/span><span class=\"o\">,<\/span> <span class=\"o\">[<\/span><span class=\"n\">e<\/span><span class=\"o\">.<\/span><span class=\"n\">text<\/span><span class=\"o\">])<\/span>\n   <span class=\"o\">]<\/span> <span class=\"k\">in<\/span>\n   <span class=\"k\">let<\/span> <span class=\"n\">cred<\/span> <span class=\"o\">=<\/span> <span class=\"o\">`<\/span><span class=\"nc\">Basic<\/span> <span class=\"o\">(<\/span><span class=\"s2\">&quot;api&quot;<\/span><span class=\"o\">,<\/span> <span class=\"n\">api_key<\/span><span class=\"o\">)<\/span> <span class=\"k\">in<\/span>\n   <span class=\"k\">let<\/span> <span class=\"n\">uri<\/span> <span class=\"o\">=<\/span> <span class=\"n\">api_base<\/span> <span class=\"o\">^<\/span> <span class=\"s2\">&quot;\/messages&quot;<\/span> <span class=\"o\">|&gt;<\/span> <span class=\"nn\">Uri<\/span><span class=\"p\">.<\/span><span class=\"n\">of_string<\/span> <span class=\"k\">in<\/span>\n   <span class=\"k\">let<\/span> <span class=\"n\">headers<\/span> <span class=\"o\">=<\/span> <span class=\"nn\">Header<\/span><span class=\"p\">.<\/span><span class=\"n\">add_authorization<\/span> <span class=\"o\">(<\/span><span class=\"nn\">Header<\/span><span class=\"p\">.<\/span><span class=\"n\">init<\/span> <span class=\"bp\">()<\/span><span class=\"o\">)<\/span> <span class=\"n\">cred<\/span> <span class=\"k\">in<\/span>\n   <span class=\"k\">let<\/span> <span class=\"n\">start<\/span> <span class=\"o\">=<\/span>\n     <span class=\"nn\">Printf<\/span><span class=\"p\">.<\/span><span class=\"n\">printf<\/span> <span class=\"s2\">&quot;Initiating email send to %s.<\/span><span class=\"se\">\\n<\/span><span class=\"s2\">&quot;<\/span> <span class=\"n\">e<\/span><span class=\"o\">.<\/span><span class=\"n\">address<\/span><span class=\"o\">;<\/span>\n     <span class=\"nn\">Unix<\/span><span class=\"p\">.<\/span><span class=\"n\">gettimeofday<\/span> <span class=\"bp\">()<\/span> <span class=\"k\">in<\/span>\n   <span class=\"k\">let<\/span><span class=\"o\">%<\/span><span class=\"n\">lwt<\/span> <span class=\"n\">resp<\/span><span class=\"o\">,<\/span> <span class=\"n\">rbody<\/span> <span class=\"o\">=<\/span> <span class=\"nn\">Client<\/span><span class=\"p\">.<\/span><span class=\"n\">post_form<\/span> <span class=\"n\">uri<\/span> <span class=\"o\">~<\/span><span class=\"n\">params<\/span> <span class=\"o\">~<\/span><span class=\"n\">headers<\/span> <span class=\"k\">in<\/span>\n   <span class=\"k\">let<\/span><span class=\"o\">%<\/span><span class=\"n\">lwt<\/span> <span class=\"n\">finish<\/span> <span class=\"o\">=<\/span> <span class=\"nn\">Unix<\/span><span class=\"p\">.<\/span><span class=\"n\">gettimeofday<\/span> <span class=\"bp\">()<\/span> <span class=\"o\">|&gt;<\/span> <span class=\"nn\">Lwt<\/span><span class=\"p\">.<\/span><span class=\"n\">return<\/span> <span class=\"k\">in<\/span>\n   <span class=\"k\">let<\/span><span class=\"o\">%<\/span><span class=\"n\">lwt<\/span> <span class=\"n\">rbody_str<\/span> <span class=\"o\">=<\/span> <span class=\"o\">(<\/span><span class=\"nn\">Cohttp_lwt<\/span><span class=\"p\">.<\/span><span class=\"nn\">Body<\/span><span class=\"p\">.<\/span><span class=\"n\">to_string<\/span> <span class=\"n\">rbody<\/span><span class=\"o\">)<\/span> <span class=\"k\">in<\/span>\n   <span class=\"nn\">Printf<\/span><span class=\"p\">.<\/span><span class=\"n\">printf<\/span> <span class=\"s2\">&quot;API Response Status: %d.<\/span><span class=\"se\">\\n<\/span><span class=\"s2\">&quot;<\/span> <span class=\"o\">(<\/span><span class=\"nn\">Code<\/span><span class=\"p\">.<\/span><span class=\"n\">code_of_status<\/span> <span class=\"n\">resp<\/span><span class=\"o\">.<\/span><span class=\"n\">status<\/span><span class=\"o\">);<\/span>\n   <span class=\"nn\">Printf<\/span><span class=\"p\">.<\/span><span class=\"n\">printf<\/span> <span class=\"s2\">&quot;API Response body %s.<\/span><span class=\"se\">\\n<\/span><span class=\"s2\">&quot;<\/span> <span class=\"n\">rbody_str<\/span><span class=\"o\">;<\/span>\n   <span class=\"nn\">Printf<\/span><span class=\"p\">.<\/span><span class=\"n\">printf<\/span> <span class=\"s2\">&quot;Time to send an email: %.2fs<\/span><span class=\"se\">\\n<\/span><span class=\"s2\">&quot;<\/span> <span class=\"o\">(<\/span><span class=\"n\">finish<\/span> <span class=\"o\">-.<\/span> <span class=\"n\">start<\/span><span class=\"o\">);<\/span>\n   <span class=\"nn\">Lwt<\/span><span class=\"p\">.<\/span><span class=\"n\">return<\/span> <span class=\"bp\">()<\/span>\n<\/code><\/pre><\/div>\n\n<p>The endpoint replies with either 200 and a JSON body like this:<\/p>\n<div class=\"highlight\"><pre><span><\/span><code><span class=\"p\">{<\/span>\n  <span class=\"nt\">&quot;id&quot;<\/span><span class=\"p\">:<\/span> <span class=\"nt\">&quot;&lt;some mailgun email address here&gt;&quot;<\/span>\n  <span class=\"nt\">&quot;message&quot;<\/span><span class=\"p\">:<\/span> <span class=\"s2\">&quot;Queued. Thank you.&quot;<\/span>\n<span class=\"p\">}<\/span>\n<\/code><\/pre><\/div>\n\n<p>or else a 400 and an explanation of why the request was rejected. In\nmy tests, a successful API request typically took between 0.5 and 1\nseconds. For comparison, the webserver can serve the email form in\nless than 200 microseconds, so the performance benefits to shifting\nemail tasks to a background queue are nontrivial.<\/p>\n<h2>Sending email with SMTP<\/h2>\n<p>Mailgun supports SMTP but they recommend using their API, especially\nfor sending large amounts of mail at once. I used\n<a href=\"https:\/\/github.com\/oxidizing\/letters\/\">letters<\/a> to test their SMTP\nsupport with this script:<\/p>\n<div class=\"highlight\"><pre><span><\/span><code><span class=\"k\">let<\/span> <span class=\"n\">body<\/span> <span class=\"o\">=<\/span> <span class=\"nn\">Letters<\/span><span class=\"p\">.<\/span><span class=\"nc\">Plain<\/span> <span class=\"o\">{|<\/span><span class=\"nc\">This<\/span> <span class=\"n\">is<\/span> <span class=\"n\">a<\/span> <span class=\"n\">test<\/span> <span class=\"n\">email<\/span> <span class=\"n\">body<\/span><span class=\"o\">.|}<\/span>\n\n<span class=\"k\">let<\/span> <span class=\"n\">send_email<\/span> <span class=\"bp\">()<\/span> <span class=\"o\">=<\/span>\n  <span class=\"k\">let<\/span> <span class=\"n\">config<\/span> <span class=\"o\">=<\/span> <span class=\"o\">(<\/span><span class=\"nn\">Letters<\/span><span class=\"p\">.<\/span><span class=\"nn\">Config<\/span><span class=\"p\">.<\/span><span class=\"n\">make<\/span>\n      <span class=\"o\">~<\/span><span class=\"n\">username<\/span><span class=\"o\">:<\/span> <span class=\"nn\">Sys<\/span><span class=\"p\">.<\/span><span class=\"n\">getenv<\/span> <span class=\"s2\">&quot;MAILGUN_SMTP_USER&quot;<\/span>\n      <span class=\"o\">~<\/span><span class=\"n\">password<\/span><span class=\"o\">:<\/span> <span class=\"nn\">Sys<\/span><span class=\"p\">.<\/span><span class=\"n\">getenv<\/span> <span class=\"s2\">&quot;MAILGUN_SMTP_PASSWORD&quot;<\/span>\n      <span class=\"o\">~<\/span><span class=\"n\">hostname<\/span><span class=\"o\">:<\/span><span class=\"s2\">&quot;smtp.mailgun.org&quot;<\/span>\n      <span class=\"o\">~<\/span><span class=\"n\">with_starttls<\/span><span class=\"o\">:<\/span><span class=\"bp\">true<\/span><span class=\"o\">)<\/span>\n  <span class=\"k\">in<\/span>\n  <span class=\"k\">let<\/span> <span class=\"n\">sender<\/span> <span class=\"o\">=<\/span> <span class=\"nn\">Sys<\/span><span class=\"p\">.<\/span><span class=\"n\">getenv<\/span> <span class=\"s2\">&quot;MAILGUN_SMTP_SENDER&quot;<\/span> <span class=\"k\">in<\/span>\n  <span class=\"k\">let<\/span> <span class=\"n\">recipients<\/span> <span class=\"o\">=<\/span> <span class=\"o\">[<\/span><span class=\"nn\">Letters<\/span><span class=\"p\">.<\/span><span class=\"nc\">To<\/span> <span class=\"o\">(<\/span><span class=\"nn\">Sys<\/span><span class=\"p\">.<\/span><span class=\"n\">getenv<\/span> <span class=\"s2\">&quot;EMAIL_ADDRESS&quot;<\/span><span class=\"o\">)]<\/span> <span class=\"k\">in<\/span>\n  <span class=\"k\">let<\/span> <span class=\"n\">subject<\/span> <span class=\"o\">=<\/span> <span class=\"s2\">&quot;Test email from mailgun.&quot;<\/span> <span class=\"k\">in<\/span>\n  <span class=\"k\">let<\/span> <span class=\"n\">mail<\/span> <span class=\"o\">=<\/span> <span class=\"nn\">Letters<\/span><span class=\"p\">.<\/span><span class=\"n\">build_email<\/span> <span class=\"o\">~<\/span><span class=\"n\">from<\/span><span class=\"o\">:<\/span><span class=\"n\">sender<\/span> <span class=\"o\">~<\/span><span class=\"n\">recipients<\/span> <span class=\"o\">~<\/span><span class=\"n\">subject<\/span> <span class=\"o\">~<\/span><span class=\"n\">body<\/span> <span class=\"k\">in<\/span>\n\n  <span class=\"nn\">Printexc<\/span><span class=\"p\">.<\/span><span class=\"n\">record_backtrace<\/span> <span class=\"bp\">true<\/span><span class=\"o\">;<\/span>\n  <span class=\"k\">match<\/span> <span class=\"n\">mail<\/span> <span class=\"k\">with<\/span>\n  <span class=\"o\">|<\/span> <span class=\"nc\">Ok<\/span> <span class=\"n\">message<\/span> <span class=\"o\">-&gt;<\/span>\n    <span class=\"o\">(<\/span><span class=\"k\">try<\/span><span class=\"o\">%<\/span><span class=\"n\">lwt<\/span>\n       <span class=\"nn\">Letters<\/span><span class=\"p\">.<\/span><span class=\"n\">send<\/span> <span class=\"o\">~<\/span><span class=\"n\">config<\/span> <span class=\"o\">~<\/span><span class=\"n\">sender<\/span> <span class=\"o\">~<\/span><span class=\"n\">recipients<\/span> <span class=\"o\">~<\/span><span class=\"n\">message<\/span>\n    <span class=\"k\">with<\/span>\n      <span class=\"n\">e<\/span> <span class=\"o\">-&gt;<\/span>\n      <span class=\"nn\">Printf<\/span><span class=\"p\">.<\/span><span class=\"n\">printf<\/span> <span class=\"s2\">&quot;Error. %s<\/span><span class=\"se\">\\n<\/span><span class=\"s2\">&quot;<\/span> <span class=\"o\">(<\/span><span class=\"nn\">Printexc<\/span><span class=\"p\">.<\/span><span class=\"n\">to_string<\/span> <span class=\"n\">e<\/span><span class=\"o\">);<\/span>\n      <span class=\"nn\">Printexc<\/span><span class=\"p\">.<\/span><span class=\"n\">print_backtrace<\/span> <span class=\"n\">stdout<\/span><span class=\"o\">;<\/span>\n      <span class=\"nn\">Lwt<\/span><span class=\"p\">.<\/span><span class=\"n\">return_unit<\/span>\n   <span class=\"o\">)<\/span>\n  <span class=\"o\">|<\/span> <span class=\"nc\">Error<\/span> <span class=\"o\">_<\/span> <span class=\"o\">-&gt;<\/span> <span class=\"nn\">Printf<\/span><span class=\"p\">.<\/span><span class=\"n\">printf<\/span> <span class=\"s2\">&quot;Message synthesis failed.&quot;<\/span><span class=\"o\">;<\/span> <span class=\"n\">flush<\/span> <span class=\"n\">stdout<\/span><span class=\"o\">;<\/span> <span class=\"nn\">Lwt<\/span><span class=\"p\">.<\/span><span class=\"n\">return_unit<\/span>\n\n\n<span class=\"k\">let<\/span> <span class=\"bp\">()<\/span> <span class=\"o\">=<\/span>\n  <span class=\"nn\">Lwt_main<\/span><span class=\"p\">.<\/span><span class=\"n\">run<\/span> <span class=\"o\">@@<\/span> <span class=\"n\">send_email<\/span> <span class=\"bp\">()<\/span>\n<\/code><\/pre><\/div>\n\n<p>I ran into some\n<a href=\"https:\/\/github.com\/oxidizing\/letters\/issues\/35\">difficulties<\/a> because\nMailgun does not consistently follow RFC 4954 (thanks to Calascibetta\nRomain for figuring out the problem and creating a\n<a href=\"https:\/\/github.com\/mirage\/colombe\/pull\/41\">patch<\/a>). Once I applied\nthe patch, I was able to send mail successfully.<\/p>\n<p>I haven't fully explored the tradeoffs of using SMTP versus an\nAPI. The main goal of my experiements was to confirm that if I needed\nto integrate with a specific SMTP server, I knew how to do so.<\/p>\n<h2>Discussion<\/h2>\n<p>This example focused on email, but task queues and background workers\ncan be used to implement other important pieces of functionality for\nweb applications. For example, I've utilized\n<a href=\"https:\/\/docs.celeryproject.org\/en\/stable\/getting-started\/introduction.html\">celery<\/a>\nin the past to generate weekly reports and schedule recurring ETL\njobs. This exercise was a nice opportunity to see how one would\nconstruct a system similar to <code>celery<\/code> in OCaml. It also provides a\nsimple illustration of how we can utilize queues to facilitate\nhorizontal scaling. If the volume of email requests grows too big for\none machine, we can put the web server and the worker on separate\ninstances or have multiple worker instances consuming from the email\nqueue.<\/p>\n<p>I didn't cover error handling in this example, but that's clearly an\nimportant piece of functionality to include when building a production\nemail system. At a minimum, it would be useful to add a retry\nmechanism in the event that Mailgun is unavailable.<\/p>\n<h2>References<\/h2>\n<p>I found the resources below helpful for working on this project:<\/p>\n<ul>\n<li>The <code>amqp-client<\/code>\n  <a href=\"https:\/\/andersfugmann.github.io\/amqp-client\/amqp-client-lwt\/index.html\">documentation<\/a>,\n  especially the\n  <a href=\"https:\/\/github.com\/andersfugmann\/amqp-client\/tree\/master\/examples\">examples<\/a>\n  were helpful for setting up with RabbitMQ.<\/li>\n<li>The <a href=\"https:\/\/github.com\/mirage\/ocaml-cohttp#client-tutorial\">client\n  tutorial<\/a>\n  was helpful for getting started with <code>cohttp<\/code>. Later, I utilized\n  <a href=\"https:\/\/mirage.github.io\/ocaml-cohttp\/cohttp-lwt-unix\/Cohttp_lwt_unix\/Client\/index.html\">this\n  section<\/a>\n  of the docs to understand that I needed to use <code>post_form<\/code> instead\n  of <code>post<\/code> when interacting with Mailgun's API.<\/li>\n<\/ul>\n<h2>Feedback<\/h2>\n<p>If you ended up looking through the source code for this example, let\nme know how what you thought! I'm interested in adding more tutorial\nresources to the OCaml ecosystem, so feel free to post a PR or issue\nto\n<a href=\"https:\/\/github.com\/jsthomas\/dream-email-example\">dream-email-example<\/a>\nif you have ideas about how to make these resources better.<\/p>","category":{"@attributes":{"term":"OCaml"}}},{"title":"Writing a REST API with Dream","link":{"@attributes":{"href":"https:\/\/jsthomas.github.io\/ocaml-dream-api.html","rel":"alternate"}},"published":"2021-07-12T00:00:00-04:00","updated":"2021-07-12T00:00:00-04:00","author":{"name":"Joe Thomas"},"id":"tag:jsthomas.github.io,2021-07-12:\/ocaml-dream-api.html","summary":"<p>Writing a REST API in Dream<\/p>","content":"<p>In the last few weeks I've been building a simple REST API using the\n<a href=\"https:\/\/aantron.github.io\/dream\/\">Dream<\/a> web framework. Writing APIs\nhas been one major component of my paid programming work and I wanted\nto compare and contrast the experience of writing an API in a strongly\ntyped functional programming language with the same workflow in a\ndynamically typed language like Python.<\/p>\n<p>You can find the source code for this project\n<a href=\"https:\/\/github.com\/jsthomas\/sensors\">here<\/a>. Hopefully, this repo will\nbe a useful resource for anyone who wants to look at a slightly larger\nexample application that uses Dream. Though I'm still a beginner, I\nwas surprised how easy it was to complete familiar tasks in this\nframework. I'm optimistic about the future of web programming in\nOCaml!<\/p>\n<p>This post provides a sort of \"experience report\" for working with\nDream, Yojson, and Caqti. Obviously, these types of reports are highly\nsubjective and you should run your own experiments too!  I'll be\ncomparing with my experience in working with\n<a href=\"https:\/\/trypyramid.com\/\">Pyramid<\/a> and\n<a href=\"https:\/\/www.sqlalchemy.org\/\">SQLAlchemy<\/a>, since those are the Python\nprojects I've used most.<\/p>\n<p>Finally, it's important to point out that Dream is in alpha (version\n<code>1.0.0~alpha2<\/code> as of this writing). This is an early version!\nComparisons with frameworks like Pyramid or Flask are in some sense\napples-and-oranges, because those projects have had a long time (and\nmany engineering hours) to mature. Ultimately, the point of this post\n(and the repo that goes with it) isn't to make make value judgements\n(\"framework X is good, Y is bad\"), but rather to understand how to\ntranslate concepts from one workflow to another.<\/p>\n<h2>Problem Definition<\/h2>\n<p>I decided to build a API for managing time series data. My\nrequirements for the project were as follows:<\/p>\n<ul>\n<li>The API will allow creating, reading, and deleting \"sensors\". A\n  sensor is an abstract IoT device that measures a floating point\n  quantity at a specific cadence (for example a weather station\n  measuring average hourly windspeed).<\/li>\n<li>Every sensor gets an API key that allows it to upload (POST) data to\n  an endpoint.<\/li>\n<li>A GET endpoint will allow users to retrieve the data a sensor\n  generated between two dates.<\/li>\n<li>The API sends and receives data formatted as JSON and must be backed\n  by a PostgreSQL database.<\/li>\n<li>The API should have <code>login\/logout<\/code> endpoints for a (not yet built)\n  frontend to use.<\/li>\n<li>Finally, a user should only be allowed to access sensor data that\n  belongs to them.<\/li>\n<\/ul>\n<p>I chose these requirements because they cover a number of different\nread\/write operations that require data formatting\/parsing and\ntracking relationships between four different entities (users, keys,\nsensors, and readings).<\/p>\n<h2>Dependencies and Setup<\/h2>\n<p>For this build, I needed three core dependencies:<\/p>\n<ol>\n<li>A server to handle web requests (Dream).<\/li>\n<li>Support for parsing and synthesizing JSON records.<\/li>\n<li>A library for integrating with PostgreSQL.<\/li>\n<\/ol>\n<p>After a bit of research, I settled on\n<a href=\"https:\/\/opam.ocaml.org\/packages\/yojson\/\">Yojson<\/a> and\n<a href=\"https:\/\/opam.ocaml.org\/packages\/caqti\/\">Caqti<\/a> for (2) and (3)\nrespectively. Both of these are fairly standard and appear in the\nexcellent corpus of\n<a href=\"https:\/\/github.com\/aantron\/dream\/tree\/master\/example\">examples<\/a> that\naccompany Dream. Since I had previously written an\n<a href=\"https:\/\/github.com\/aantron\/dream\/tree\/master\/example\/w-docker-postgres\">example<\/a>\nof how to use Dream with a dockerized PostrgreSQL container, I used\nthat as a starting point.<\/p>\n<p>It's useful to have a way to run (and re-run) ad-hoc requests against\nthe API during development. I used <a href=\"https:\/\/insomnia.rest\/\">Insomnia<\/a>\nfor this, but other tools like <code>curl<\/code> would work too.<\/p>\n<h2>Adding an endpoint<\/h2>\n<p>To give a sense of my development workflow, I want to walk through my\nprocess for adding a simple endpoint, <code>\/api\/login<\/code>. Inside the router,\nthat endpoint looks like:<\/p>\n<div class=\"highlight\"><pre><span><\/span><code><span class=\"nn\">Dream<\/span><span class=\"p\">.<\/span><span class=\"n\">post<\/span> <span class=\"s2\">&quot;\/api\/login&quot;<\/span> <span class=\"n\">login<\/span><span class=\"o\">;<\/span>\n<\/code><\/pre><\/div>\n\n<p>In this excerpt <code>login<\/code> is a \"handler\". Handlers are responsible for\ntranslating requests into responses; this is captured in their <a href=\"https:\/\/aantron.github.io\/dream\/#type-handler\">type\nsignature<\/a>.<\/p>\n<p>Conceptually, the <code>login<\/code> handler needs to do three things:<\/p>\n<ol>\n<li>Receive a JSON body and confirm it's formatted as expected.<\/li>\n<li>Look up the relevant user\/password combination in the database.<\/li>\n<li>Load the relevant session information if the credentials are valid.<\/li>\n<\/ol>\n<p>For the first part, the endpoint needs to receive a JSON payload that\nlooks like <code>{\"username\": \"...\", \"password\": \"...\"}<\/code>. To describe that\npayload, I introduced a simple record type:<\/p>\n<div class=\"highlight\"><pre><span><\/span><code><span class=\"k\">type<\/span> <span class=\"n\">login_doc<\/span> <span class=\"o\">=<\/span> <span class=\"o\">{<\/span>\n  <span class=\"n\">username<\/span> <span class=\"o\">:<\/span> <span class=\"kt\">string<\/span><span class=\"o\">;<\/span>\n  <span class=\"n\">password<\/span> <span class=\"o\">:<\/span> <span class=\"kt\">string<\/span><span class=\"o\">;<\/span>\n<span class=\"o\">}<\/span> <span class=\"o\">[@@<\/span><span class=\"n\">deriving<\/span> <span class=\"n\">yojson<\/span><span class=\"o\">]<\/span>\n<\/code><\/pre><\/div>\n\n<p>Adding <code>[@@deriving yojson]<\/code> means the compiler can generate functions\nto convert these records to and from JSON. In this case those\nfunctions are called <code>login_doc_of_yojson<\/code> and <code>yojson_of_login_doc<\/code>.<\/p>\n<p>My <code>login<\/code> handler looked roughly like this:<\/p>\n<div class=\"highlight\"><pre><span><\/span><code><span class=\"k\">let<\/span> <span class=\"n\">json_receiver<\/span> <span class=\"n\">json_parser<\/span> <span class=\"n\">handler<\/span> <span class=\"n\">request<\/span> <span class=\"o\">=<\/span>\n  <span class=\"k\">let<\/span><span class=\"o\">%<\/span><span class=\"n\">lwt<\/span> <span class=\"n\">body<\/span> <span class=\"o\">=<\/span> <span class=\"nn\">Dream<\/span><span class=\"p\">.<\/span><span class=\"n\">body<\/span> <span class=\"n\">request<\/span> <span class=\"k\">in<\/span>\n  <span class=\"k\">let<\/span> <span class=\"n\">parse<\/span> <span class=\"o\">=<\/span>\n    <span class=\"k\">try<\/span>\n      <span class=\"nc\">Some<\/span> <span class=\"o\">(<\/span><span class=\"n\">body<\/span>\n      <span class=\"o\">|&gt;<\/span> <span class=\"nn\">Yojson<\/span><span class=\"p\">.<\/span><span class=\"nn\">Safe<\/span><span class=\"p\">.<\/span><span class=\"n\">from_string<\/span>\n      <span class=\"o\">|&gt;<\/span> <span class=\"n\">json_parser<\/span><span class=\"o\">)<\/span>\n    <span class=\"k\">with<\/span> <span class=\"o\">_<\/span> <span class=\"o\">-&gt;<\/span>\n      <span class=\"nc\">None<\/span>\n  <span class=\"k\">in<\/span>\n  <span class=\"k\">match<\/span> <span class=\"n\">parse<\/span> <span class=\"k\">with<\/span>\n  <span class=\"o\">|<\/span> <span class=\"nc\">Some<\/span> <span class=\"n\">doc<\/span> <span class=\"o\">-&gt;<\/span> <span class=\"n\">handler<\/span> <span class=\"n\">doc<\/span> <span class=\"n\">request<\/span>\n  <span class=\"o\">|<\/span> <span class=\"nc\">None<\/span> <span class=\"o\">-&gt;<\/span>\n    <span class=\"o\">{<\/span> <span class=\"n\">error<\/span><span class=\"o\">=<\/span><span class=\"s2\">&quot;Received invalid JSON input.&quot;<\/span> <span class=\"o\">}<\/span>\n    <span class=\"o\">|&gt;<\/span> <span class=\"n\">yojson_of_error_doc<\/span>\n    <span class=\"o\">|&gt;<\/span> <span class=\"n\">json_response<\/span> <span class=\"o\">~<\/span><span class=\"n\">status<\/span><span class=\"o\">:<\/span> <span class=\"o\">`<\/span><span class=\"nc\">Bad_Request<\/span>\n\n\n<span class=\"k\">let<\/span> <span class=\"n\">login<\/span> <span class=\"o\">=<\/span>\n  <span class=\"k\">let<\/span> <span class=\"n\">login_base<\/span> <span class=\"n\">login_doc<\/span> <span class=\"n\">request<\/span> <span class=\"o\">=<\/span>\n    <span class=\"k\">let<\/span><span class=\"o\">%<\/span><span class=\"n\">lwt<\/span> <span class=\"n\">user_id<\/span> <span class=\"o\">=<\/span> <span class=\"nn\">Dream<\/span><span class=\"p\">.<\/span><span class=\"n\">sql<\/span> <span class=\"n\">request<\/span>\n        <span class=\"o\">(<\/span><span class=\"nn\">Models<\/span><span class=\"p\">.<\/span><span class=\"nn\">User<\/span><span class=\"p\">.<\/span><span class=\"n\">get<\/span> <span class=\"n\">login_doc<\/span><span class=\"o\">.<\/span><span class=\"n\">username<\/span> <span class=\"n\">login_doc<\/span><span class=\"o\">.<\/span><span class=\"n\">password<\/span><span class=\"o\">)<\/span> <span class=\"k\">in<\/span>\n    <span class=\"k\">match<\/span> <span class=\"n\">user_id<\/span> <span class=\"k\">with<\/span>\n    <span class=\"o\">|<\/span> <span class=\"nc\">Some<\/span> <span class=\"n\">id<\/span> <span class=\"o\">-&gt;<\/span>\n      <span class=\"k\">let<\/span><span class=\"o\">%<\/span><span class=\"n\">lwt<\/span> <span class=\"bp\">()<\/span> <span class=\"o\">=<\/span> <span class=\"nn\">Dream<\/span><span class=\"p\">.<\/span><span class=\"n\">invalidate_session<\/span> <span class=\"n\">request<\/span> <span class=\"k\">in<\/span>\n      <span class=\"k\">let<\/span><span class=\"o\">%<\/span><span class=\"n\">lwt<\/span> <span class=\"bp\">()<\/span> <span class=\"o\">=<\/span> <span class=\"nn\">Dream<\/span><span class=\"p\">.<\/span><span class=\"n\">put_session<\/span> <span class=\"s2\">&quot;user&quot;<\/span> <span class=\"o\">(<\/span><span class=\"nn\">Int<\/span><span class=\"p\">.<\/span><span class=\"n\">to_string<\/span> <span class=\"n\">id<\/span><span class=\"o\">)<\/span> <span class=\"n\">request<\/span> <span class=\"k\">in<\/span>\n      <span class=\"nn\">Dream<\/span><span class=\"p\">.<\/span><span class=\"n\">empty<\/span> <span class=\"o\">`<\/span><span class=\"nc\">OK<\/span>\n    <span class=\"o\">|<\/span> <span class=\"nc\">None<\/span> <span class=\"o\">-&gt;<\/span> <span class=\"nn\">Dream<\/span><span class=\"p\">.<\/span><span class=\"n\">empty<\/span> <span class=\"o\">`<\/span><span class=\"nc\">Forbidden<\/span>\n  <span class=\"k\">in<\/span>\n  <span class=\"n\">json_receiver<\/span> <span class=\"n\">login_doc_of_yojson<\/span> <span class=\"n\">login_base<\/span>\n<\/code><\/pre><\/div>\n\n<p>If a user uploads an invalid JSON body, this will cause\n<code>login_doc_of_yojson<\/code> to throw an exception. By default, this produces\na 500 server error response. To handle this situation more gracefully,\nI introduced <code>json_receiver<\/code>. If the parser passed to <code>json_receiver<\/code>\nsucceeds on the request body, the results are passed to the inner\nhandler. Otherwise, the server responds with a <code>400 Bad\nRequest<\/code>. Re-using <code>json_receiver<\/code> across my endpoints allows me to\navoid introducing a<code>try\/with<\/code> block any time time I need to handle\nJSON input.<\/p>\n<p>I decided to manage models in a separate library, <code>Models<\/code>. The\nbuild tool, <code>dune<\/code>, made this easy to do; I just needed separate\n<code>dune<\/code> files for the <code>server\/model<\/code> and <code>server\/bin<\/code> folders. I like\nthis design because it simplifies re-use of the database portion of my\nproject. For example, if I later needed to build a CLI admin tool,\nthat tool could utilize my existing queries without being exposed to\nAPI concerns.<\/p>\n<p>Inside <code>User<\/code>, the <code>get<\/code> query function is defined as:<\/p>\n<div class=\"highlight\"><pre><span><\/span><code><span class=\"k\">let<\/span> <span class=\"n\">get<\/span> <span class=\"o\">=<\/span>\n  <span class=\"k\">let<\/span> <span class=\"n\">query<\/span> <span class=\"o\">=<\/span>\n    <span class=\"nn\">R<\/span><span class=\"p\">.<\/span><span class=\"n\">find_opt<\/span> <span class=\"nn\">T<\/span><span class=\"p\">.<\/span><span class=\"o\">(<\/span><span class=\"n\">tup2<\/span> <span class=\"nn\">T<\/span><span class=\"p\">.<\/span><span class=\"n\">string<\/span> <span class=\"nn\">T<\/span><span class=\"p\">.<\/span><span class=\"n\">string<\/span><span class=\"o\">)<\/span> <span class=\"nn\">T<\/span><span class=\"p\">.<\/span><span class=\"n\">int<\/span>\n      <span class=\"s2\">&quot;SELECT id FROM app_user WHERE username = ? and password = ?&quot;<\/span> <span class=\"k\">in<\/span>\n  <span class=\"k\">fun<\/span> <span class=\"n\">username<\/span> <span class=\"n\">password<\/span> <span class=\"o\">(<\/span><span class=\"k\">module<\/span> <span class=\"nc\">Db<\/span> <span class=\"o\">:<\/span> <span class=\"nc\">DB<\/span><span class=\"o\">)<\/span> <span class=\"o\">-&gt;<\/span>\n    <span class=\"k\">let<\/span><span class=\"o\">%<\/span><span class=\"n\">lwt<\/span> <span class=\"n\">user_or_error<\/span> <span class=\"o\">=<\/span> <span class=\"nn\">Db<\/span><span class=\"p\">.<\/span><span class=\"n\">find_opt<\/span> <span class=\"n\">query<\/span> <span class=\"o\">(<\/span><span class=\"n\">username<\/span><span class=\"o\">,<\/span> <span class=\"n\">password<\/span><span class=\"o\">)<\/span> <span class=\"k\">in<\/span>\n    <span class=\"nn\">Caqti_lwt<\/span><span class=\"p\">.<\/span><span class=\"n\">or_fail<\/span> <span class=\"n\">user_or_error<\/span>\n<\/code><\/pre><\/div>\n\n<p>Caqti allows us to define a function that consumes our query\nparameters (the username and password) along with a database\nconnection, and produces a promise that will resolve with the results\nof the query. In this case, the types encode that the function\nproduces an <code>int option<\/code> containing the user's primary key if the\ncredentials are valid. (Note that it's not a good idea to store\npasswords in plain text like this; this is just for illustrative\npurposes.)<\/p>\n<p>Session management, the final item that the endpoint needs to address,\nis handled by Dream. The framework allows sessions to be stored in\ncookies, memory, or the database; I opted for database sessions\nbecause I had used similar session backends in the past. Sessions\nallow us to store pairs key\/value strings across requests. I used the\nsession just to store the logged-in user's ID, so that the API has\neasy access in later database queries.<\/p>\n<h2>Thoughts on the Dream Router<\/h2>\n<p>The final router for my server looked like this:<\/p>\n<div class=\"highlight\"><pre><span><\/span><code><span class=\"k\">let<\/span> <span class=\"bp\">()<\/span> <span class=\"o\">=<\/span>\n  <span class=\"nn\">Dream<\/span><span class=\"p\">.<\/span><span class=\"n\">run<\/span> <span class=\"o\">~<\/span><span class=\"n\">interface<\/span><span class=\"o\">:<\/span><span class=\"s2\">&quot;0.0.0.0&quot;<\/span>\n  <span class=\"o\">@@<\/span> <span class=\"nn\">Dream<\/span><span class=\"p\">.<\/span><span class=\"n\">logger<\/span>\n  <span class=\"o\">@@<\/span> <span class=\"nn\">Dream<\/span><span class=\"p\">.<\/span><span class=\"n\">sql_pool<\/span> <span class=\"s2\">&quot;postgresql:\/\/sensors@127.0.0.1\/sensors&quot;<\/span>\n  <span class=\"o\">@@<\/span> <span class=\"nn\">Dream<\/span><span class=\"p\">.<\/span><span class=\"n\">sql_sessions<\/span>\n  <span class=\"o\">@@<\/span> <span class=\"nn\">Dream<\/span><span class=\"p\">.<\/span><span class=\"n\">router<\/span> <span class=\"o\">[<\/span>\n    <span class=\"c\">(* More endpoints here ... *)<\/span>\n\n    <span class=\"nn\">Dream<\/span><span class=\"p\">.<\/span><span class=\"n\">get<\/span> <span class=\"s2\">&quot;\/version&quot;<\/span> <span class=\"n\">version<\/span><span class=\"o\">;<\/span>\n    <span class=\"nn\">Dream<\/span><span class=\"p\">.<\/span><span class=\"n\">post<\/span> <span class=\"s2\">&quot;\/api\/login&quot;<\/span> <span class=\"n\">login<\/span><span class=\"o\">;<\/span>\n    <span class=\"nn\">Dream<\/span><span class=\"p\">.<\/span><span class=\"n\">post<\/span> <span class=\"s2\">&quot;\/api\/logout&quot;<\/span> <span class=\"n\">logout<\/span><span class=\"o\">;<\/span>\n\n    <span class=\"nn\">Dream<\/span><span class=\"p\">.<\/span><span class=\"n\">scope<\/span> <span class=\"s2\">&quot;\/api&quot;<\/span> <span class=\"o\">[<\/span><span class=\"n\">login_required<\/span><span class=\"o\">]<\/span> <span class=\"o\">[<\/span>\n      <span class=\"nn\">Dream<\/span><span class=\"p\">.<\/span><span class=\"n\">get<\/span> <span class=\"s2\">&quot;\/user\/:user_id&quot;<\/span> <span class=\"n\">user<\/span><span class=\"o\">;<\/span>\n      <span class=\"c\">(* More endpoints here... *)<\/span>\n    <span class=\"o\">];<\/span>\n\n    <span class=\"nn\">Dream<\/span><span class=\"p\">.<\/span><span class=\"n\">scope<\/span> <span class=\"s2\">&quot;\/sensor&quot;<\/span> <span class=\"bp\">[]<\/span> <span class=\"o\">[<\/span>\n      <span class=\"nn\">Dream<\/span><span class=\"p\">.<\/span><span class=\"n\">post<\/span> <span class=\"s2\">&quot;\/upload&quot;<\/span> <span class=\"o\">@@<\/span> <span class=\"n\">api_key_required<\/span> <span class=\"n\">sensor_upload<\/span><span class=\"o\">;<\/span>\n    <span class=\"o\">]<\/span>\n  <span class=\"o\">]<\/span>\n  <span class=\"o\">@@<\/span> <span class=\"nn\">Dream<\/span><span class=\"p\">.<\/span><span class=\"n\">not_found<\/span>\n<\/code><\/pre><\/div>\n\n<p>I really appreciate how Dream makes it possible to get a concise\noverview of the API; in some Pyramid projects, I found this wasn't\nalways possible. In fact, in Pyramid I sometimes struggled with subtle\nrouting bugs that were not obvious until run time. Having the compiler\nvalidate the router in Dream was a welcome change.<\/p>\n<p>At the moment, Pyramid makes it somewhat easier to handle\naccess\/permissions concerns compared to Dream. Working in Pyramid, it\nwas relatively common for the routes to manage some amount of\nparameter validation and permissions. For example, given a path\n<code>\/user\/123\/article\/abc456<\/code>, the route (or \"resources\" in Pyramid\nterminology) would be responsible for:<\/p>\n<ul>\n<li>Extracting the user and article IDs (<code>123<\/code> and <code>abc456<\/code>).<\/li>\n<li>Determining those records actually exist in the database, and\n  passing them to the view\/handler in a context record.<\/li>\n<li>Validating that the requester has permissions to operate on those\nUser and Article records.<\/li>\n<\/ul>\n<p>This is discussed a bit more in the Pyramid Docs under <a href=\"https:\/\/docs.pylonsproject.org\/projects\/pyramid\/en\/latest\/narr\/traversal.html\">URL\ntraversal<\/a>.\nEffectively, Pyramid resources mean that handler\/view code downstream\ncan focus on updating database records and\/or rendering HTML\/JSON\nwithout worrying about permissions concerns.<\/p>\n<p>I didn't want to build a permissions system for my API so instead I\nincorporated User IDs into my function signatures in <code>Model<\/code> and used\ninner joins to model permissions. For example, here is an example of a\nquery that fetches the metadata for all sensors belonging to a\nparticular user:<\/p>\n<div class=\"highlight\"><pre><span><\/span><code><span class=\"k\">SELECT<\/span> <span class=\"n\">s<\/span><span class=\"p\">.<\/span><span class=\"n\">name<\/span><span class=\"p\">,<\/span> <span class=\"n\">s<\/span><span class=\"p\">.<\/span><span class=\"n\">description<\/span><span class=\"p\">,<\/span> <span class=\"n\">k<\/span><span class=\"p\">.<\/span><span class=\"n\">uuid<\/span>\n<span class=\"k\">FROM<\/span> <span class=\"n\">sensor<\/span> <span class=\"n\">s<\/span>\n<span class=\"k\">INNER<\/span> <span class=\"k\">JOIN<\/span> <span class=\"n\">user_sensor<\/span> <span class=\"n\">us<\/span>\n <span class=\"k\">ON<\/span> <span class=\"n\">us<\/span><span class=\"p\">.<\/span><span class=\"n\">sensor<\/span> <span class=\"o\">=<\/span> <span class=\"n\">s<\/span><span class=\"p\">.<\/span><span class=\"n\">id<\/span> <span class=\"k\">AND<\/span> <span class=\"n\">us<\/span><span class=\"p\">.<\/span><span class=\"n\">app_user<\/span> <span class=\"o\">=<\/span> <span class=\"err\">$<\/span><span class=\"mi\">1<\/span> <span class=\"k\">AND<\/span> <span class=\"n\">us<\/span><span class=\"p\">.<\/span><span class=\"n\">sensor<\/span> <span class=\"o\">=<\/span> <span class=\"err\">$<\/span><span class=\"mi\">2<\/span>\n<span class=\"k\">INNER<\/span> <span class=\"k\">JOIN<\/span> <span class=\"n\">api_key<\/span> <span class=\"n\">k<\/span>\n <span class=\"k\">ON<\/span> <span class=\"n\">s<\/span><span class=\"p\">.<\/span><span class=\"n\">api_key<\/span> <span class=\"o\">=<\/span> <span class=\"n\">k<\/span><span class=\"p\">.<\/span><span class=\"n\">id<\/span>\n<\/code><\/pre><\/div>\n\n<p>By joining against <code>user_sensor<\/code>, I ensure that a user only gets data\nfor the sensors they own.<\/p>\n<p>I should point out that Dream allows us to use a custom router,\nhowever! The project has <a href=\"https:\/\/github.com\/aantron\/dream\/issues\/122\">an\nissue<\/a> for more elaborate\nrouting and Ulrik Strid has introduced\n<a href=\"https:\/\/github.com\/ulrikstrid\/dream-routes\">dream-routes<\/a>, which\nallows additional type information to be encoded in routes. So,\nwriting a more sophisticated router that behaves like Pyramid's\nresource system is certainly possible.<\/p>\n<h2>Comparing Caqti and SQLAlchemy<\/h2>\n<p>As a web programmer, especially one working on an analytics project,\nit's important to get comfortable working with the database library\nyou've chosen for your project. Indeed, a significant portion of this\nproject consisted of familiarizing myself with <code>Caqti<\/code>.<\/p>\n<p>Caqti is a bit different from SQLAlchemy. With SQLAlchemy, you\ntypically define one class for each table. Then, using SQLAlchemy's\nmetaprogramming features, those classes are used to define\nqueries. For comparison, here are equivalent queries against the user\ntable:<\/p>\n<p><strong>Caqti<\/strong><\/p>\n<div class=\"highlight\"><pre><span><\/span><code><span class=\"k\">let<\/span> <span class=\"n\">get<\/span> <span class=\"o\">=<\/span>\n  <span class=\"k\">let<\/span> <span class=\"n\">query<\/span> <span class=\"o\">=<\/span>\n    <span class=\"nn\">R<\/span><span class=\"p\">.<\/span><span class=\"n\">find_opt<\/span> <span class=\"nn\">T<\/span><span class=\"p\">.<\/span><span class=\"o\">(<\/span><span class=\"n\">tup2<\/span> <span class=\"nn\">T<\/span><span class=\"p\">.<\/span><span class=\"n\">string<\/span> <span class=\"nn\">T<\/span><span class=\"p\">.<\/span><span class=\"n\">string<\/span><span class=\"o\">)<\/span> <span class=\"nn\">T<\/span><span class=\"p\">.<\/span><span class=\"n\">int<\/span>\n      <span class=\"s2\">&quot;SELECT id FROM app_user WHERE username = ? and password = ?&quot;<\/span> <span class=\"k\">in<\/span>\n  <span class=\"k\">fun<\/span> <span class=\"n\">username<\/span> <span class=\"n\">password<\/span> <span class=\"o\">(<\/span><span class=\"k\">module<\/span> <span class=\"nc\">Db<\/span> <span class=\"o\">:<\/span> <span class=\"nc\">DB<\/span><span class=\"o\">)<\/span> <span class=\"o\">-&gt;<\/span>\n    <span class=\"k\">let<\/span><span class=\"o\">%<\/span><span class=\"n\">lwt<\/span> <span class=\"n\">user_or_error<\/span> <span class=\"o\">=<\/span> <span class=\"nn\">Db<\/span><span class=\"p\">.<\/span><span class=\"n\">find_opt<\/span> <span class=\"n\">query<\/span> <span class=\"o\">(<\/span><span class=\"n\">username<\/span><span class=\"o\">,<\/span> <span class=\"n\">password<\/span><span class=\"o\">)<\/span> <span class=\"k\">in<\/span>\n    <span class=\"nn\">Caqti_lwt<\/span><span class=\"p\">.<\/span><span class=\"n\">or_fail<\/span> <span class=\"n\">user_or_error<\/span>\n<\/code><\/pre><\/div>\n\n<p><strong>SQLAlchemy<\/strong><\/p>\n<div class=\"highlight\"><pre><span><\/span><code><span class=\"n\">db<\/span><span class=\"o\">.<\/span><span class=\"n\">session<\/span><span class=\"o\">.<\/span><span class=\"n\">query<\/span><span class=\"p\">(<\/span><span class=\"n\">User<\/span><span class=\"p\">)<\/span> \\\n    <span class=\"o\">.<\/span><span class=\"n\">filter<\/span><span class=\"p\">(<\/span>\n        <span class=\"n\">User<\/span><span class=\"o\">.<\/span><span class=\"n\">username<\/span> <span class=\"o\">==<\/span> <span class=\"n\">username<\/span><span class=\"p\">,<\/span>\n        <span class=\"n\">User<\/span><span class=\"o\">.<\/span><span class=\"n\">password<\/span> <span class=\"o\">==<\/span> <span class=\"n\">password<\/span>\n    <span class=\"p\">)<\/span><span class=\"o\">.<\/span><span class=\"n\">one_or_none<\/span><span class=\"p\">()<\/span>\n<\/code><\/pre><\/div>\n\n<p>Working with Caqti, a mistake in the syntax of a SQL query won't be\ndiscovered until runtime. I made fewer mistakes like this with\nSQLAlchemy because most queries are written in Python and can be\nlinted by the IDE. Another recurring point of confusion for me with\nCaqti had to do with matching the function on the <code>Caqti_request<\/code>\n(<code>R.find_opt<\/code> above) with the function invoked in <code>Db<\/code>\n(<code>Db.find_opt<\/code>); this is how we indicate that the query produces zero,\none, zero\/one, or multiple rows. If the two don't agree, the program\nwon't compile; initially I struggled to understand what this\ncompiler error meant:<\/p>\n<div class=\"highlight\"><pre><span><\/span><code><span class=\"n\">Error<\/span><span class=\"o\">:<\/span> <span class=\"n\">The<\/span> <span class=\"kd\">function<\/span> <span class=\"n\">applied<\/span> <span class=\"n\">to<\/span> <span class=\"k\">this<\/span> <span class=\"n\">argument<\/span> <span class=\"n\">has<\/span> <span class=\"n\">type<\/span>\n         <span class=\"o\">?<\/span><span class=\"n\">env<\/span><span class=\"o\">:(<\/span><span class=\"n\">Caqti_driver_info<\/span><span class=\"o\">.<\/span><span class=\"na\">t<\/span> <span class=\"o\">-&gt;<\/span> <span class=\"n\">string<\/span> <span class=\"o\">-&gt;<\/span> <span class=\"n\">Caqti_query<\/span><span class=\"o\">.<\/span><span class=\"na\">t<\/span><span class=\"o\">)<\/span> <span class=\"o\">-&gt;<\/span>\n         <span class=\"o\">?<\/span><span class=\"n\">oneshot<\/span><span class=\"o\">:<\/span><span class=\"n\">bool<\/span> <span class=\"o\">-&gt;<\/span>\n         <span class=\"o\">(<\/span><span class=\"err\">&#39;<\/span><span class=\"n\">a<\/span><span class=\"o\">,<\/span> <span class=\"n\">unit<\/span><span class=\"o\">,<\/span> <span class=\"o\">[&lt;<\/span> <span class=\"err\">`<\/span><span class=\"n\">Many<\/span> <span class=\"o\">|<\/span> <span class=\"err\">`<\/span><span class=\"n\">One<\/span> <span class=\"o\">|<\/span> <span class=\"err\">`<\/span><span class=\"n\">Zero<\/span> <span class=\"o\">&gt;<\/span> <span class=\"err\">`<\/span><span class=\"n\">Zero<\/span> <span class=\"o\">])<\/span> <span class=\"n\">Caqti_request<\/span><span class=\"o\">.<\/span><span class=\"na\">t<\/span>\n<span class=\"n\">This<\/span> <span class=\"n\">argument<\/span> <span class=\"n\">cannot<\/span> <span class=\"n\">be<\/span> <span class=\"n\">applied<\/span> <span class=\"n\">without<\/span> <span class=\"n\">label<\/span>\n<\/code><\/pre><\/div>\n\n<p>Using Caqti became easier as I became accustomed to thinking in terms of\nprepared queries. About halfway through the project I realized I\nneeded to switch from SQLite to PostgreSQL, and changing databases was\nfairly painless because Caqti supports both.<\/p>\n<p>I also made use of Caqti's features for dealing with custom column\ntypes. Caqti does not have built-in support for JSON columns, but\nadding a custom column type to handle this was straightforward:<\/p>\n<div class=\"highlight\"><pre><span><\/span><code><span class=\"n\">type<\/span><span class=\"w\"> <\/span><span class=\"n\">readings<\/span><span class=\"w\"> <\/span><span class=\"o\">=<\/span><span class=\"w\"> <\/span><span class=\"nc\">float<\/span><span class=\"w\"> <\/span><span class=\"k\">option<\/span><span class=\"w\"> <\/span><span class=\"k\">array<\/span><span class=\"w\"> <\/span><span class=\"o\">[<\/span><span class=\"n\">@@deriving yojson<\/span><span class=\"o\">]<\/span><span class=\"w\"><\/span>\n\n<span class=\"n\">let<\/span><span class=\"w\"> <\/span><span class=\"n\">sql_readings<\/span><span class=\"w\"> <\/span><span class=\"o\">=<\/span><span class=\"w\"><\/span>\n<span class=\"w\">  <\/span><span class=\"n\">let<\/span><span class=\"w\"> <\/span><span class=\"n\">encode<\/span><span class=\"w\"> <\/span><span class=\"p\">(<\/span><span class=\"nl\">a<\/span><span class=\"p\">:<\/span><span class=\"w\"> <\/span><span class=\"n\">readings<\/span><span class=\"p\">)<\/span><span class=\"w\"> <\/span><span class=\"o\">=<\/span><span class=\"w\"><\/span>\n<span class=\"w\">    <\/span><span class=\"n\">Ok<\/span><span class=\"w\"> <\/span><span class=\"p\">(<\/span><span class=\"n\">a<\/span><span class=\"w\"> <\/span><span class=\"o\">|&gt;<\/span><span class=\"w\"> <\/span><span class=\"n\">yojson_of_readings<\/span><span class=\"w\"> <\/span><span class=\"o\">|&gt;<\/span><span class=\"w\"> <\/span><span class=\"n\">Yojson<\/span><span class=\"p\">.<\/span><span class=\"n\">Safe<\/span><span class=\"p\">.<\/span><span class=\"n\">to_string<\/span><span class=\"p\">)<\/span><span class=\"w\"><\/span>\n<span class=\"w\">  <\/span><span class=\"ow\">in<\/span><span class=\"w\"><\/span>\n<span class=\"w\">  <\/span><span class=\"n\">let<\/span><span class=\"w\"> <\/span><span class=\"n\">decode<\/span><span class=\"w\"> <\/span><span class=\"nc\">text<\/span><span class=\"w\"> <\/span><span class=\"o\">=<\/span><span class=\"w\"><\/span>\n<span class=\"w\">    <\/span><span class=\"n\">Ok<\/span><span class=\"w\"> <\/span><span class=\"p\">(<\/span><span class=\"nc\">text<\/span><span class=\"w\"> <\/span><span class=\"o\">|&gt;<\/span><span class=\"w\"> <\/span><span class=\"n\">Yojson<\/span><span class=\"p\">.<\/span><span class=\"n\">Safe<\/span><span class=\"p\">.<\/span><span class=\"n\">from_string<\/span><span class=\"w\"> <\/span><span class=\"o\">|&gt;<\/span><span class=\"w\"> <\/span><span class=\"n\">readings_of_yojson<\/span><span class=\"p\">)<\/span><span class=\"w\"><\/span>\n<span class=\"w\">  <\/span><span class=\"ow\">in<\/span><span class=\"w\"><\/span>\n<span class=\"w\">  <\/span><span class=\"n\">T<\/span><span class=\"p\">.(<\/span><span class=\"n\">custom<\/span><span class=\"w\"> <\/span><span class=\"o\">~<\/span><span class=\"n\">encode<\/span><span class=\"w\"> <\/span><span class=\"o\">~<\/span><span class=\"n\">decode<\/span><span class=\"w\"> <\/span><span class=\"n\">string<\/span><span class=\"p\">)<\/span><span class=\"w\"><\/span>\n<\/code><\/pre><\/div>\n\n<p>In my case, the JSON that I needed to store consisted of arrays of\nfloating point numbers, so building the custom type was simply a\nmatter of connecting Yojson and Caqti in the right way.<\/p>\n<h2>Discussion<\/h2>\n<p>Ever since I started building web applications in Python, I've thought\nof an API server as a big function that transforms requests into\nresponses, with any nontrivial state residing in databases or services\nlike S3. Dream provides a modern web framework that matches my mental\nmodel for how a web server should work.<\/p>\n<p>Web programming in OCaml \"feels\" a bit different than working in\nPython. In Python it's possible to get something running quickly, but\nit's also easy to forget corner cases and introduce defects that have\nto be addressed later in the application's lifecycle. An OCaml project\nrequires some up-front investment, but this investment pays off later\nin several ways. First, fast feedback from the compiler (together with\neditor integrations like <code>merlin<\/code> and <code>tuareg<\/code>) helped me to identify\nissues earlier. <code>Yojson<\/code> made it simple to enforce that JSON requests\nand responses adhered to a fixed schema, and helped me process inputs\nmore systematically. OCaml made refactoring safe and easy, so that I\ncould confidently adapt my design as I introduced new requirements. In\nthe right context, I think the advantages of using OCaml could\nsignificantly reduce the total lifecycle costs of maintaining many web\napplications without reducing the pace of new development.<\/p>\n<h2>References<\/h2>\n<p>I found the resources below helpful for working on this project:<\/p>\n<ul>\n<li>The Dream <a href=\"https:\/\/aantron.github.io\/dream\/\">API docs<\/a> set a high\n  standard for readability and helped me quickly get up to speed with\n  the framework.<\/li>\n<li>This <a href=\"https:\/\/github.com\/aantron\/dream\/tree\/master\/example\">section<\/a>\n  of the Dream repo has excellent examples, both for working with the\n  framework and deploying it.<\/li>\n<li>I referred to Bobby Priambodo's <a href=\"https:\/\/medium.com\/@bobbypriambodo\/interfacing-ocaml-and-postgresql-with-caqti-a92515bdaa11\">blog\n  posts<\/a>\n  about interfacing Caqti and PostgreSQL as I wrote the models in my project.<\/li>\n<li>The Caqti\n  <a href=\"https:\/\/paurkedal.github.io\/ocaml-caqti\/index.html\">docs<\/a>,\n  especially for <code>Caqti_type<\/code> and <code>Caqti_request<\/code> were helpful as I\n  was writing queries.<\/li>\n<li>There is also an\n  <a href=\"https:\/\/github.com\/paurkedal\/ocaml-caqti\/blob\/master\/tests\/bikereg.ml\">example<\/a>\n  in the Caqti repo that is worth looking through.<\/li>\n<li>The README on\n  <a href=\"https:\/\/github.com\/janestreet\/ppx_yojson_conv\">ppx_yojson_conv<\/a> had\n  helpful examples that I referred to while writing my own\n  JSON-related types.<\/li>\n<\/ul>\n<h2>Feedback<\/h2>\n<p>If you ended up looking through the source code for my API, let me\nknow how what you thought! I'm interested in adding more tutorial\nresources to the OCaml ecosystem, so feel free to post a PR or issue\nto\n<a href=\"https:\/\/github.com\/jsthomas\/sensors\">sensors<\/a>\nif you have ideas about how to make these resources better.<\/p>","category":{"@attributes":{"term":"OCaml"}}},{"title":"Let's write a shell in OCaml!","link":{"@attributes":{"href":"https:\/\/jsthomas.github.io\/ocaml-shell.html","rel":"alternate"}},"published":"2021-07-01T00:00:00-04:00","updated":"2021-07-01T00:00:00-04:00","author":{"name":"Joe Thomas"},"id":"tag:jsthomas.github.io,2021-07-01:\/ocaml-shell.html","summary":"<p>A user experience report about writing a simple shell in OCaml<\/p>","content":"<p>This Summer I'm studying OCaml and systems programming at the <a href=\"https:\/\/www.recurse.com\/\">Recurse\nCenter<\/a>. Currently I'm reading the\ndelightful book <a href=\"https:\/\/pages.cs.wisc.edu\/~remzi\/OSTEP\/\"><em>Operating Systems: Three Easy\nPieces<\/em><\/a> by Remzi\nArpaci-Dusseau and Andrea Arpaci-Dusseau. Besides great exposition,\nthe book includes several interesting projects, one of which is to\n<a href=\"https:\/\/github.com\/remzi-arpacidusseau\/ostep-projects\/tree\/master\/processes-shell\">write a\nshell<\/a>.<\/p>\n<p>The project materials, a set of shell scripts that define tests, are\nlanguage agnostic. I believe the authors intended for students to use\nC, but I worked through the exercise in OCaml; you can find the final\nresult <a href=\"https:\/\/github.com\/jsthomas\/simple-ocaml-shell\">in this\nrepo<\/a>. This blog post\nis a short experience report; if you're interested in working on a\nbeginner OCaml project, hopefully it provides some useful scaffolding\nfor your studies.<\/p>\n<h2>Shell features<\/h2>\n<p>The shell I built (<code>osh<\/code>) has a somewhat limited feature set. It:<\/p>\n<ul>\n<li>\n<p>Allows several commands to be run in parallel (e.g. <code>program1 arg1 &amp;\n  program2 arg2 arg3<\/code>)<\/p>\n<\/li>\n<li>\n<p>Supports simple output redirection (e.g. <code>echo \"hello\" &gt;\n  hello.txt<\/code>). Both <code>stdout<\/code> and <code>stderr<\/code> go to the same file.<\/p>\n<\/li>\n<li>\n<p>Has three builtin functions, <code>cd<\/code>, <code>exit<\/code>, and <code>path<\/code>. <code>path<\/code> allows\n  you to define a list of directories to search for executables; we\n  need this because environment variables aren't supported.<\/p>\n<\/li>\n<\/ul>\n<p>Other niceties, like tab completion and pipes, aren't supported. To\nfacilitate testing, the shell can run in a batch mode (<code>osh &lt;my file\nof commands&gt;<\/code>) as well as an interactive mode. A final simplifying\nassumption is that <code>osh<\/code> only provides a basic error message when\ninputs are malformed.<\/p>\n<h2>Concepts<\/h2>\n<p>There are three main topics I studied while working on this project:<\/p>\n<ol>\n<li>\n<p>The <code>Unix<\/code> module, especially <code>fork<\/code> and\n    <code>execv<\/code>. <a href=\"https:\/\/ocaml.github.io\/ocamlunix\/ocamlunix.html\">This\n    page<\/a>, from\n    Xavier Leroy and Didier R\u00e9my, was helpful for getting up to\n    speed. The man-pages were also useful.<\/p>\n<\/li>\n<li>\n<p>The <a href=\"https:\/\/ocaml.org\/api\/Stream.html\"><code>Stream<\/code><\/a> module. Streams\n   in OCaml are roughly analogous to generators in Python; they\n   allowed me to use a single type (a <code>string Stream.t<\/code>) to represent\n   commands coming from an interactive session or a batch file.<\/p>\n<\/li>\n<li>\n<p>The <a href=\"https:\/\/github.com\/inhabitedtype\/angstrom\">Angstrom<\/a>\n   parser-combinator library. I used this library to determine whether\n   a given line of user input is well formed.<\/p>\n<\/li>\n<\/ol>\n<p>I suspect you could implement the parser without Angstrom, if you\nreally wanted to. I wanted to learn more about this library, and this\nproject seemed like a good place to try it out.<\/p>\n<p>Although I previously worked through some simple monadic parser\nexercises in Haskell, I struggled the most with Angstrom. Reading one\nof the main <a href=\"https:\/\/github.com\/inhabitedtype\/angstrom\/blob\/master\/lib\/angstrom.mli\">mli\nfiles<\/a>\nseemed to be the best way to get an overview of the combinators the\nlibrary provides. I also spent a fair amount of time experimenting in\n<code>utop<\/code> as I put my parser together.<\/p>\n<h2>Steps<\/h2>\n<p>Here is a rough outline for how I built my shell.<\/p>\n<p>First, I defined a main function that would fetch a line of text from\n<code>stdin<\/code> and echo it back to the user. Then I added the ability to\nrepresent either interactive or batch input with a <code>Stream<\/code>:<\/p>\n<div class=\"highlight\"><pre><span><\/span><code><span class=\"k\">let<\/span> <span class=\"n\">prompt_stream<\/span> <span class=\"o\">=<\/span>\n  <span class=\"k\">let<\/span> <span class=\"n\">f<\/span> <span class=\"o\">_<\/span> <span class=\"o\">=<\/span>\n    <span class=\"nn\">Printf<\/span><span class=\"p\">.<\/span><span class=\"n\">printf<\/span> <span class=\"s2\">&quot;osh&gt; &quot;<\/span><span class=\"o\">;<\/span>\n    <span class=\"nc\">Some<\/span> <span class=\"o\">(<\/span><span class=\"n\">read_line<\/span> <span class=\"bp\">()<\/span><span class=\"o\">)<\/span> <span class=\"k\">in<\/span>\n  <span class=\"nn\">Stream<\/span><span class=\"p\">.<\/span><span class=\"n\">from<\/span> <span class=\"n\">f<\/span>\n\n\n<span class=\"k\">let<\/span> <span class=\"n\">file_stream<\/span> <span class=\"n\">filename<\/span> <span class=\"o\">=<\/span>\n  <span class=\"k\">let<\/span> <span class=\"n\">in_channel<\/span> <span class=\"o\">=<\/span> <span class=\"n\">open_in<\/span> <span class=\"n\">filename<\/span> <span class=\"k\">in<\/span>\n  <span class=\"k\">let<\/span> <span class=\"n\">f<\/span> <span class=\"o\">_<\/span> <span class=\"o\">=<\/span>\n    <span class=\"k\">try<\/span>\n      <span class=\"nc\">Some<\/span> <span class=\"o\">(<\/span><span class=\"n\">input_line<\/span> <span class=\"n\">in_channel<\/span><span class=\"o\">)<\/span>\n    <span class=\"k\">with<\/span> <span class=\"nc\">End_of_file<\/span> <span class=\"o\">-&gt;<\/span>\n      <span class=\"n\">close_in<\/span> <span class=\"n\">in_channel<\/span><span class=\"o\">;<\/span>\n      <span class=\"nc\">None<\/span>\n  <span class=\"k\">in<\/span>\n  <span class=\"nn\">Stream<\/span><span class=\"p\">.<\/span><span class=\"n\">from<\/span> <span class=\"n\">f<\/span>\n<\/code><\/pre><\/div>\n\n<p>It's useful to do this part as early as possible, since batch input\nallows you to run the tests.<\/p>\n<p>Once I could get <code>osh<\/code> to fail all 22 test cases, I started adding the\nsimpler built-in commands <code>cd<\/code> and <code>exit<\/code>. (Note <code>.\/test-osh.sh -c<\/code>\nwill run all 22 tests, without stopping at the first one that fails.)<\/p>\n<p>My first version of <code>main<\/code> just treated user input as <code>string list<\/code>:<\/p>\n<div class=\"highlight\"><pre><span><\/span><code><span class=\"k\">let<\/span> <span class=\"k\">rec<\/span> <span class=\"n\">main<\/span> <span class=\"n\">stream<\/span> <span class=\"o\">=<\/span>\n  <span class=\"k\">let<\/span> <span class=\"n\">parse<\/span> <span class=\"n\">text<\/span> <span class=\"o\">=<\/span> <span class=\"nn\">String<\/span><span class=\"p\">.<\/span><span class=\"n\">split_on_char<\/span> <span class=\"sc\">&#39; &#39;<\/span> <span class=\"n\">text<\/span> <span class=\"k\">in<\/span>\n  <span class=\"k\">let<\/span> <span class=\"n\">process<\/span> <span class=\"n\">text<\/span> <span class=\"o\">=<\/span>\n    <span class=\"k\">match<\/span> <span class=\"n\">parse<\/span> <span class=\"n\">text<\/span> <span class=\"k\">with<\/span>\n    <span class=\"o\">|<\/span> <span class=\"bp\">[]<\/span> <span class=\"o\">-&gt;<\/span> <span class=\"n\">main<\/span> <span class=\"n\">stream<\/span>  <span class=\"c\">(* Empty lines should just be treated as no-ops. *)<\/span>\n    <span class=\"o\">|<\/span> <span class=\"o\">[<\/span><span class=\"s2\">&quot;&quot;<\/span><span class=\"o\">]<\/span> <span class=\"o\">-&gt;<\/span> <span class=\"n\">main<\/span> <span class=\"n\">stream<\/span>\n    <span class=\"o\">|<\/span> <span class=\"o\">[<\/span><span class=\"s2\">&quot;exit&quot;<\/span><span class=\"o\">]<\/span> <span class=\"o\">-&gt;<\/span> <span class=\"n\">exit<\/span> <span class=\"mi\">0<\/span>\n    <span class=\"o\">|<\/span> <span class=\"o\">[<\/span><span class=\"s2\">&quot;cd&quot;<\/span><span class=\"o\">;<\/span> <span class=\"n\">x<\/span><span class=\"o\">]<\/span> <span class=\"o\">-&gt;<\/span> <span class=\"nn\">Unix<\/span><span class=\"p\">.<\/span><span class=\"n\">chdir<\/span> <span class=\"n\">x<\/span>\n    <span class=\"o\">|<\/span> <span class=\"s2\">&quot;cd&quot;<\/span><span class=\"o\">::<\/span> <span class=\"o\">_<\/span> <span class=\"o\">-&gt;<\/span> <span class=\"n\">print_error<\/span> <span class=\"bp\">()<\/span>\n    <span class=\"o\">|<\/span> <span class=\"n\">x<\/span><span class=\"o\">::<\/span><span class=\"n\">xs<\/span> <span class=\"o\">-&gt;<\/span>\n      <span class=\"k\">match<\/span> <span class=\"nn\">Unix<\/span><span class=\"p\">.<\/span><span class=\"n\">fork<\/span> <span class=\"bp\">()<\/span> <span class=\"k\">with<\/span>\n      <span class=\"o\">|<\/span> <span class=\"mi\">0<\/span> <span class=\"o\">-&gt;<\/span> <span class=\"c\">(* Child *)<\/span>\n        <span class=\"nn\">Unix<\/span><span class=\"p\">.<\/span><span class=\"n\">execv<\/span> <span class=\"n\">x<\/span> <span class=\"o\">(<\/span><span class=\"nn\">Array<\/span><span class=\"p\">.<\/span><span class=\"n\">of_list<\/span> <span class=\"n\">xs<\/span><span class=\"o\">)<\/span>\n      <span class=\"o\">|<\/span> <span class=\"n\">child_pid<\/span> <span class=\"o\">-&gt;<\/span> <span class=\"c\">(* Parent *)<\/span>\n        <span class=\"k\">let<\/span> <span class=\"o\">_<\/span> <span class=\"o\">=<\/span> <span class=\"nn\">Unix<\/span><span class=\"p\">.<\/span><span class=\"n\">waitpid<\/span> <span class=\"bp\">[]<\/span> <span class=\"n\">child_pid<\/span>\n        <span class=\"k\">in<\/span> <span class=\"bp\">()<\/span>\n  <span class=\"k\">in<\/span>\n  <span class=\"nn\">Stream<\/span><span class=\"p\">.<\/span><span class=\"n\">iter<\/span> <span class=\"n\">process<\/span> <span class=\"n\">stream<\/span>\n<\/code><\/pre><\/div>\n\n<p>This worked well enough for running simple commands like <code>\/usr\/bin\/ls\n-lah<\/code>. In order to get output redirection and <code>&amp;<\/code> to work, I needed to\nupgrade the program's parsing capabilities. I switched from\nrepresenting user input with a <code>string list<\/code> to a variant type:<\/p>\n<div class=\"highlight\"><pre><span><\/span><code><span class=\"k\">type<\/span> <span class=\"n\">exec<\/span> <span class=\"o\">=<\/span> <span class=\"o\">{<\/span>\n  <span class=\"n\">executable<\/span><span class=\"o\">:<\/span> <span class=\"kt\">string<\/span><span class=\"o\">;<\/span>\n  <span class=\"n\">arguments<\/span><span class=\"o\">:<\/span> <span class=\"kt\">string<\/span> <span class=\"kt\">list<\/span><span class=\"o\">;<\/span>\n  <span class=\"n\">output<\/span><span class=\"o\">:<\/span> <span class=\"kt\">string<\/span> <span class=\"n\">option<\/span><span class=\"o\">;<\/span>\n<span class=\"o\">}<\/span>\n\n<span class=\"k\">type<\/span> <span class=\"n\">line<\/span> <span class=\"o\">=<\/span>\n  <span class=\"o\">|<\/span> <span class=\"nc\">NoOp<\/span>\n  <span class=\"o\">|<\/span> <span class=\"nc\">ChangeDirectory<\/span> <span class=\"k\">of<\/span> <span class=\"kt\">string<\/span>\n  <span class=\"o\">|<\/span> <span class=\"nc\">PathChange<\/span> <span class=\"k\">of<\/span> <span class=\"kt\">string<\/span> <span class=\"kt\">list<\/span>\n  <span class=\"o\">|<\/span> <span class=\"nc\">Executable<\/span> <span class=\"k\">of<\/span> <span class=\"n\">exec<\/span> <span class=\"kt\">list<\/span>\n  <span class=\"o\">|<\/span> <span class=\"nc\">Quit<\/span>\n<\/code><\/pre><\/div>\n\n<p>I found the OCaml compiler (and its emacs integrations, <code>merlin<\/code> and\n<code>tuareg<\/code>) very helpful for refactoring. When I revised my types to\nmake them better reflect the data I wanted to model, type errors\nidentified all of the places I needed to update. At this point, I\nintroduced an Angstrom parser and re-implemented support for <code>cd<\/code>,\n<code>exit<\/code>, and <code>path<\/code>. That allowed me to get familiar with the parser\ncombinators <code>*&gt;<\/code>, <code>many<\/code>, and <code>choice<\/code>, before attempting the more\ncomplicated parsers needed to support <code>&amp;<\/code> and <code>&gt;<\/code>.<\/p>\n<p>The type system protected me from a number of silly mistakes, but it\nwasn't a silver bullet. I spent an hour confused about why one of my\nparsers would go into an infinite loop before realizing I needed to\nuse <code>many1<\/code> instead of <code>many<\/code>. I think this is the sort of mistake I\nwould learn to avoid if I spent more time working with Angstrom.<\/p>\n<h2>Discussion<\/h2>\n<p>As I worked through this project, I started to appreciate how OCaml\nchooses \"good defaults\" for my code (especially immutable data)\nwithout forbidding me from working in an imperative mode when I need\nto.<\/p>\n<p>For example, I found that the function responsible for running a child\nprocess was most natural to express with imperative language features:<\/p>\n<div class=\"highlight\"><pre><span><\/span><code><span class=\"k\">let<\/span> <span class=\"n\">run_executable<\/span> <span class=\"n\">path<\/span> <span class=\"o\">{<\/span><span class=\"n\">executable<\/span><span class=\"o\">;<\/span> <span class=\"n\">arguments<\/span><span class=\"o\">;<\/span> <span class=\"n\">output<\/span><span class=\"o\">}<\/span> <span class=\"o\">=<\/span>\n  <span class=\"k\">let<\/span> <span class=\"n\">full_paths<\/span> <span class=\"o\">=<\/span> <span class=\"nn\">List<\/span><span class=\"p\">.<\/span><span class=\"n\">map<\/span> <span class=\"o\">(<\/span><span class=\"k\">fun<\/span> <span class=\"n\">p<\/span> <span class=\"o\">-&gt;<\/span> <span class=\"n\">p<\/span> <span class=\"o\">^<\/span> <span class=\"s2\">&quot;\/&quot;<\/span> <span class=\"o\">^<\/span> <span class=\"n\">executable<\/span><span class=\"o\">)<\/span> <span class=\"n\">path<\/span> <span class=\"k\">in<\/span>\n  <span class=\"k\">let<\/span> <span class=\"n\">executables<\/span> <span class=\"o\">=<\/span> <span class=\"nn\">List<\/span><span class=\"p\">.<\/span><span class=\"n\">append<\/span> <span class=\"n\">full_paths<\/span> <span class=\"o\">[<\/span><span class=\"n\">executable<\/span><span class=\"o\">]<\/span> <span class=\"k\">in<\/span>\n  <span class=\"k\">let<\/span> <span class=\"n\">present<\/span> <span class=\"o\">=<\/span> <span class=\"nn\">List<\/span><span class=\"p\">.<\/span><span class=\"n\">filter<\/span> <span class=\"n\">executable_present<\/span> <span class=\"n\">executables<\/span> <span class=\"k\">in<\/span>\n\n  <span class=\"k\">match<\/span> <span class=\"n\">present<\/span> <span class=\"k\">with<\/span>\n  <span class=\"o\">|<\/span> <span class=\"bp\">[]<\/span> <span class=\"o\">-&gt;<\/span> <span class=\"n\">print_error<\/span> <span class=\"bp\">()<\/span><span class=\"o\">;<\/span> <span class=\"nc\">None<\/span>\n  <span class=\"o\">|<\/span> <span class=\"n\">x<\/span> <span class=\"o\">::<\/span> <span class=\"o\">_<\/span> <span class=\"o\">-&gt;<\/span>\n    <span class=\"k\">match<\/span> <span class=\"nn\">Unix<\/span><span class=\"p\">.<\/span><span class=\"n\">fork<\/span> <span class=\"bp\">()<\/span> <span class=\"k\">with<\/span>\n    <span class=\"o\">|<\/span> <span class=\"mi\">0<\/span> <span class=\"o\">-&gt;<\/span> <span class=\"c\">(* Child *)<\/span>\n       <span class=\"k\">let<\/span> <span class=\"n\">out<\/span> <span class=\"o\">=<\/span> <span class=\"k\">match<\/span> <span class=\"n\">output<\/span> <span class=\"k\">with<\/span>\n         <span class=\"o\">|<\/span> <span class=\"nc\">Some<\/span> <span class=\"n\">filename<\/span> <span class=\"o\">-&gt;<\/span> <span class=\"nn\">Unix<\/span><span class=\"p\">.<\/span><span class=\"n\">openfile<\/span> <span class=\"n\">filename<\/span> <span class=\"o\">[<\/span><span class=\"nn\">Unix<\/span><span class=\"p\">.<\/span><span class=\"nc\">O_TRUNC<\/span><span class=\"o\">;<\/span> <span class=\"nn\">Unix<\/span><span class=\"p\">.<\/span><span class=\"nc\">O_WRONLY<\/span><span class=\"o\">;<\/span> <span class=\"nn\">Unix<\/span><span class=\"p\">.<\/span><span class=\"nc\">O_CREAT<\/span> <span class=\"o\">]<\/span> <span class=\"mo\">0o640<\/span>\n         <span class=\"o\">|<\/span> <span class=\"nc\">None<\/span> <span class=\"o\">-&gt;<\/span> <span class=\"nn\">Unix<\/span><span class=\"p\">.<\/span><span class=\"n\">stdout<\/span>\n       <span class=\"k\">in<\/span>\n       <span class=\"k\">let<\/span> <span class=\"n\">err<\/span> <span class=\"o\">=<\/span> <span class=\"k\">match<\/span> <span class=\"n\">output<\/span> <span class=\"k\">with<\/span>\n         <span class=\"o\">|<\/span> <span class=\"nc\">None<\/span> <span class=\"o\">-&gt;<\/span> <span class=\"nn\">Unix<\/span><span class=\"p\">.<\/span><span class=\"n\">stderr<\/span>\n         <span class=\"o\">|<\/span> <span class=\"o\">_<\/span> <span class=\"o\">-&gt;<\/span> <span class=\"n\">out<\/span>\n       <span class=\"k\">in<\/span>\n       <span class=\"nn\">Unix<\/span><span class=\"p\">.<\/span><span class=\"n\">dup2<\/span> <span class=\"n\">out<\/span> <span class=\"nn\">Unix<\/span><span class=\"p\">.<\/span><span class=\"n\">stdout<\/span><span class=\"o\">;<\/span>\n       <span class=\"nn\">Unix<\/span><span class=\"p\">.<\/span><span class=\"n\">dup2<\/span> <span class=\"n\">err<\/span> <span class=\"nn\">Unix<\/span><span class=\"p\">.<\/span><span class=\"n\">stderr<\/span><span class=\"o\">;<\/span>\n       <span class=\"nn\">Unix<\/span><span class=\"p\">.<\/span><span class=\"n\">execv<\/span> <span class=\"n\">x<\/span> <span class=\"o\">@@<\/span> <span class=\"nn\">Array<\/span><span class=\"p\">.<\/span><span class=\"n\">of_list<\/span> <span class=\"o\">@@<\/span> <span class=\"n\">executable<\/span><span class=\"o\">::<\/span><span class=\"n\">arguments<\/span><span class=\"o\">;<\/span>\n    <span class=\"o\">|<\/span> <span class=\"n\">child_pid<\/span> <span class=\"o\">-&gt;<\/span> <span class=\"c\">(* Parent *)<\/span>\n      <span class=\"nc\">Some<\/span> <span class=\"n\">child_pid<\/span>\n<\/code><\/pre><\/div>\n\n<p>Writing this way made it easy for me to switch between C and OCaml; in\nboth languages, we follow a pattern of calling <code>fork<\/code>, then <code>execv<\/code> in\nthe child process. The fact that I can easily re-use my knowledge of\nthe UNIX APIs across different programming languages is one of the\nmain reasons I'm excited to learn more systems programming concepts!<\/p>\n<p>Variants and pattern matching are features I miss when working in\nlanguages like Python. These features make it so easy to look at a\nfunction like:<\/p>\n<div class=\"highlight\"><pre><span><\/span><code><span class=\"k\">let<\/span> <span class=\"n\">main<\/span> <span class=\"n\">stream<\/span> <span class=\"o\">=<\/span>\n  <span class=\"k\">let<\/span> <span class=\"n\">path<\/span> <span class=\"o\">=<\/span> <span class=\"n\">ref<\/span> <span class=\"o\">[<\/span><span class=\"s2\">&quot;\/bin&quot;<\/span><span class=\"o\">]<\/span> <span class=\"k\">in<\/span>\n  <span class=\"k\">let<\/span> <span class=\"n\">process<\/span> <span class=\"n\">text<\/span> <span class=\"o\">=<\/span>\n    <span class=\"k\">match<\/span> <span class=\"nn\">Parser<\/span><span class=\"p\">.<\/span><span class=\"n\">parse_line<\/span> <span class=\"n\">text<\/span> <span class=\"k\">with<\/span>\n    <span class=\"o\">|<\/span> <span class=\"nc\">Error<\/span> <span class=\"o\">_<\/span> <span class=\"o\">-&gt;<\/span> <span class=\"n\">print_error<\/span> <span class=\"bp\">()<\/span>\n    <span class=\"o\">|<\/span> <span class=\"nc\">Ok<\/span> <span class=\"o\">(<\/span><span class=\"nc\">NoOp<\/span><span class=\"o\">)<\/span> <span class=\"o\">-&gt;<\/span> <span class=\"bp\">()<\/span> <span class=\"c\">(* Empty lines should just be treated as no-ops. *)<\/span>\n    <span class=\"o\">|<\/span> <span class=\"nc\">Ok<\/span> <span class=\"o\">(<\/span><span class=\"nc\">Quit<\/span><span class=\"o\">)<\/span> <span class=\"o\">-&gt;<\/span> <span class=\"n\">exit<\/span> <span class=\"mi\">0<\/span>\n    <span class=\"o\">|<\/span> <span class=\"nc\">Ok<\/span> <span class=\"o\">(<\/span><span class=\"nc\">ChangeDirectory<\/span> <span class=\"n\">x<\/span><span class=\"o\">)<\/span> <span class=\"o\">-&gt;<\/span> <span class=\"n\">change_directory<\/span> <span class=\"n\">x<\/span>\n    <span class=\"o\">|<\/span> <span class=\"nc\">Ok<\/span> <span class=\"o\">(<\/span><span class=\"nc\">PathChange<\/span> <span class=\"n\">paths<\/span><span class=\"o\">)<\/span> <span class=\"o\">-&gt;<\/span>\n      <span class=\"k\">let<\/span> <span class=\"n\">cwd<\/span> <span class=\"o\">=<\/span> <span class=\"nn\">Unix<\/span><span class=\"p\">.<\/span><span class=\"n\">getcwd<\/span> <span class=\"bp\">()<\/span> <span class=\"k\">in<\/span>\n      <span class=\"n\">path<\/span> <span class=\"o\">:=<\/span> <span class=\"nn\">List<\/span><span class=\"p\">.<\/span><span class=\"n\">map<\/span> <span class=\"o\">(<\/span><span class=\"n\">amend_path<\/span> <span class=\"n\">cwd<\/span><span class=\"o\">)<\/span> <span class=\"n\">paths<\/span>\n    <span class=\"o\">|<\/span> <span class=\"nc\">Ok<\/span> <span class=\"o\">(<\/span><span class=\"nc\">Executable<\/span> <span class=\"n\">execs<\/span><span class=\"o\">)<\/span> <span class=\"o\">-&gt;<\/span> <span class=\"n\">run_executables<\/span> <span class=\"o\">!<\/span><span class=\"n\">path<\/span> <span class=\"n\">execs<\/span>\n  <span class=\"k\">in<\/span>\n  <span class=\"nn\">Stream<\/span><span class=\"p\">.<\/span><span class=\"n\">iter<\/span> <span class=\"n\">process<\/span> <span class=\"n\">stream<\/span>\n<\/code><\/pre><\/div>\n\n<p>and quickly understand all of the different commands <code>osh<\/code> supports.<\/p>\n<p>Although it took me some time to get up and running with Angstrom, I\nstrongly prefer working with parser combinators to writing an\nimperative parser (as I've had to do in Python and Java). Angstrom\nmakes it easy to build up small parsers and test them in isolation\nbefore composing them into the larger parser you really need. If I\nplanned to develop a shell with more features, I would probably break\n<code>Parser<\/code> out into its own file with separate unit tests.<\/p>\n<h2>Feedback<\/h2>\n<p>If you give this project a try, let me know how it turned out! I'm\ninterested in adding more tutorial resources to the OCaml ecosystem,\nso feel free to post a PR or issue to\n<a href=\"https:\/\/github.com\/jsthomas\/simple-ocaml-shell\">simple-ocaml-shell<\/a>\nif you have ideas about how to make these resources better.<\/p>","category":{"@attributes":{"term":"OCaml"}}},{"title":"Microbenchmarking Implementations of Map in OCaml","link":{"@attributes":{"href":"https:\/\/jsthomas.github.io\/map-comparison.html","rel":"alternate"}},"published":"2017-06-06T00:00:00-04:00","updated":"2017-06-06T00:00:00-04:00","author":{"name":"Joe Thomas"},"id":"tag:jsthomas.github.io,2017-06-06:\/map-comparison.html","summary":"<p>A comparison of different implementations of map in OCaml<\/p>","content":"<p><code>Map<\/code> is one of the first higher-order functions I remember\nencountering when I learned some rudimentary functional programming\ntopics as an undergraduate. More recently I began learning OCaml. The\n<code>map<\/code>\n<a href=\"https:\/\/github.com\/ocaml\/ocaml\/blob\/2691c40f2ff9bc34912db39bc1f17045c9241473\/stdlib\/list.ml#L80-L82\">implementation<\/a>\nI found in the standard library was the textbook definition I was\nexpecting<\/p>\n<div class=\"highlight\"><pre><span><\/span><code><span class=\"k\">let<\/span> <span class=\"k\">rec<\/span> <span class=\"n\">map<\/span> <span class=\"n\">f<\/span> <span class=\"o\">=<\/span> <span class=\"k\">function<\/span>\n   <span class=\"bp\">[]<\/span> <span class=\"o\">-&gt;<\/span> <span class=\"bp\">[]<\/span>\n  <span class=\"o\">|<\/span> <span class=\"n\">a<\/span><span class=\"o\">::<\/span><span class=\"n\">l<\/span> <span class=\"o\">-&gt;<\/span> <span class=\"k\">let<\/span> <span class=\"n\">r<\/span> <span class=\"o\">=<\/span> <span class=\"n\">f<\/span> <span class=\"n\">a<\/span> <span class=\"k\">in<\/span> <span class=\"n\">r<\/span> <span class=\"o\">::<\/span> <span class=\"n\">map<\/span> <span class=\"n\">f<\/span> <span class=\"n\">l<\/span>\n<\/code><\/pre><\/div>\n\n<p>but I was surprised to learn there are actually several\nimplementations of <code>map<\/code> in the OCaml ecosystem. I wanted to know more\nabout these different implementations and their performance\ncharacteristics. This article summarizes what I learned.<\/p>\n<p>Part of my motivation to write this post arose from\n<a href=\"https:\/\/github.com\/ocsigen\/lwt\/pull\/347\">this discussion<\/a> of a pull\nrequest that proposes the default <code>map<\/code> implementation in <code>lwt<\/code> should\nbe tail recursive. After reading all of the comments, I wanted to\ndevelop experiments that would convince me whether this was a good\nidea.<\/p>\n<h1>Introduction<\/h1>\n<p>Since I'll introduce several versions of <code>map<\/code>, I'll refer to the\nimplementation above as <code>stdlib<\/code>. An important aspect of this version\nis that it isn't <em>tail recursive<\/em>. A tail recursive function uses\nrecursion in a specific way; it only calls itself as the final\noperation in the function. In OCaml, tail recursive functions get the\nbenefit of tail-call optimization so that they only use one frame on\nthe stack. In contrast, the <code>stdlib<\/code> implementation takes space on the\nstack proportional to the length of the input list. For long enough\nlists, this causes a stack overflow.<\/p>\n<p>We can make a basic tail-recursive version of <code>map<\/code> by composing two\nstandard library functions that are tail recursive: <code>List.rev_map<\/code>\n(which creates the output of <code>map<\/code>, but in reversed order) and\n<code>List.rev<\/code> which reverses lists. I'll call this naive implementation\n<code>ntr<\/code> (naive tail recursive). Compared to <code>stdlib<\/code>, <code>ntr<\/code> allocates\ntwice as much space on the heap (one list for the output of\n<code>List.rev_map<\/code>, and a second equally long list for <code>List.rev<\/code>) and\nspends additional time performing a list traversal. The benefit is\nthat with this implementation, calling <code>map<\/code> on a long list won't\nresult in a stack overflow.<\/p>\n<p>As we'll see later in the Results section, the naive tail recursive\nimplementation is, overall, slower than the <code>stdlib<\/code>\nimplementation. However, there are some optimizations we can apply to\nimprove the performance of both versions.<\/p>\n<p>The first trick I call \"unrolling\". Similar to\n<a href=\"https:\/\/en.wikipedia.org\/wiki\/Loop_unrolling\">loop unrolling in procedural languages<\/a>,\nthe idea is to use cases to <code>map<\/code> on groups of list elements so fewer\nfunction calls are needed to complete the work. For example, an\nunrolled version of <code>stdlib<\/code> looks like:<\/p>\n<div class=\"highlight\"><pre><span><\/span><code><span class=\"k\">let<\/span> <span class=\"k\">rec<\/span> <span class=\"n\">map<\/span> <span class=\"n\">f<\/span> <span class=\"n\">l<\/span> <span class=\"o\">=<\/span>\n  <span class=\"k\">match<\/span> <span class=\"n\">l<\/span> <span class=\"k\">with<\/span>\n  <span class=\"o\">|<\/span> <span class=\"bp\">[]<\/span> <span class=\"o\">-&gt;<\/span> <span class=\"bp\">[]<\/span>\n  <span class=\"o\">|<\/span> <span class=\"o\">[<\/span><span class=\"n\">x1<\/span><span class=\"o\">]<\/span> <span class=\"o\">-&gt;<\/span>\n    <span class=\"k\">let<\/span> <span class=\"n\">f1<\/span> <span class=\"o\">=<\/span> <span class=\"n\">f<\/span> <span class=\"n\">x1<\/span> <span class=\"k\">in<\/span>\n    <span class=\"o\">[<\/span><span class=\"n\">f1<\/span><span class=\"o\">]<\/span>\n  <span class=\"o\">|<\/span> <span class=\"o\">[<\/span><span class=\"n\">x1<\/span><span class=\"o\">;<\/span> <span class=\"n\">x2<\/span><span class=\"o\">]<\/span> <span class=\"o\">-&gt;<\/span>\n    <span class=\"k\">let<\/span> <span class=\"n\">f1<\/span> <span class=\"o\">=<\/span> <span class=\"n\">f<\/span> <span class=\"n\">x1<\/span> <span class=\"k\">in<\/span>\n    <span class=\"k\">let<\/span> <span class=\"n\">f2<\/span> <span class=\"o\">=<\/span> <span class=\"n\">f<\/span> <span class=\"n\">x2<\/span> <span class=\"k\">in<\/span>\n    <span class=\"o\">[<\/span><span class=\"n\">f1<\/span><span class=\"o\">;<\/span> <span class=\"n\">f2<\/span><span class=\"o\">]<\/span>\n  <span class=\"o\">|<\/span> <span class=\"n\">x1<\/span> <span class=\"o\">::<\/span> <span class=\"n\">x2<\/span> <span class=\"o\">::<\/span> <span class=\"n\">x3<\/span> <span class=\"o\">::<\/span> <span class=\"n\">tl<\/span> <span class=\"o\">-&gt;<\/span>\n    <span class=\"k\">let<\/span> <span class=\"n\">f1<\/span> <span class=\"o\">=<\/span> <span class=\"n\">f<\/span> <span class=\"n\">x1<\/span> <span class=\"k\">in<\/span>\n    <span class=\"k\">let<\/span> <span class=\"n\">f2<\/span> <span class=\"o\">=<\/span> <span class=\"n\">f<\/span> <span class=\"n\">x2<\/span> <span class=\"k\">in<\/span>\n    <span class=\"k\">let<\/span> <span class=\"n\">f3<\/span> <span class=\"o\">=<\/span> <span class=\"n\">f<\/span> <span class=\"n\">x3<\/span> <span class=\"k\">in<\/span>\n    <span class=\"n\">f1<\/span> <span class=\"o\">::<\/span> <span class=\"n\">f2<\/span> <span class=\"o\">::<\/span> <span class=\"n\">f3<\/span> <span class=\"o\">::<\/span> <span class=\"n\">map<\/span> <span class=\"n\">tl<\/span>\n<\/code><\/pre><\/div>\n\n<p>We get to choose how many elements to unroll (here I picked 3); some\nprofiling is needed to decide the most appropriate number.<\/p>\n<p>The second trick I call \"hybridizing\". The <code>stdlib<\/code> version is faster,\nbut isn't safe for long lists. The tail recursive implementation is\nslow, but safe for all lists. When we \"hybridize\" the two, we use the\nfaster version up to some fixed number of elements (e.g. 1000), and\nthen switch to the safe version for the remainder of the list.<\/p>\n<p>These two optimizations are useful for understanding the\nimplementations of <code>map<\/code> we find in other libraries. For example, both\n<a href=\"https:\/\/github.com\/janestreet\/base\/blob\/f10483e957206dc6b656a28ffec667d8b068c149\/src\/list.ml#L311-L345\"><code>base<\/code><\/a>\nand\n<a href=\"https:\/\/github.com\/c-cube\/ocaml-containers\/blob\/d659ba677e3dbd95430f59b3794ac2f2a5677d61\/src\/core\/CCList.ml#L20-L37\"><code>containers<\/code><\/a>\nuse an unrolled <code>stdlib<\/code>-style <code>map<\/code>, hybridized with an\n<code>ntr<\/code>-style <code>map<\/code>.<\/p>\n<p>Looking at <code>ntr<\/code>, one might ask: Is it strictly necessary to use\nadditional heap space to get the implementation to be tail recursive?\nThe answer is no. The <code>batteries<\/code> package\n<a href=\"https:\/\/github.com\/ocaml-batteries-team\/batteries-included\/blob\/c10c65a203a7590b15b9a370f66e8c2884817428\/src\/batList.mlv#L163-L173\">implements <code>map<\/code><\/a>\nso that the work is done by a single tail recursive function, creating\none new list on the heap. To achieve this, the implementation uses\nmutable state and casting to avoid a second list traversal\n(specifically,\n<a href=\"https:\/\/github.com\/ocaml-batteries-team\/batteries-included\/blob\/c10c65a203a7590b15b9a370f66e8c2884817428\/src\/batList.mlv#L69\">here<\/a>).<\/p>\n<p>As with any optimization, one makes tradeoffs between elegance,\nperformance, and the language features one considers acceptable to\nuse. I wanted to know:<\/p>\n<ul>\n<li>\n<p>Which version is the fastest in practice?<\/p>\n<\/li>\n<li>\n<p>How much speed does one lose using the safer tail recursive version?<\/p>\n<\/li>\n<\/ul>\n<p>Both <code>base<\/code> and <code>containers<\/code> decided to hybridize with an <code>ntr<\/code>-style\n<code>map<\/code> for safety. But the <code>batteries<\/code> implementation is also robust to\nstack overflow. That led to one final question:<\/p>\n<ul>\n<li>How fast is an unrolled <code>stdlib<\/code>-style <code>map<\/code> hybridized with a\n  <code>batteries<\/code>-style <code>map<\/code>?<\/li>\n<\/ul>\n<h1>Experimental Setup<\/h1>\n<p>In 2014, Jane Street introduced a\n<a href=\"https:\/\/github.com\/janestreet\/core_bench\">library<\/a> for\nmicrobenchmarking called <code>core_bench<\/code>. As they explain\n<a href=\"https:\/\/blogs.janestreet.com\/core_bench-micro-benchmarking-for-ocaml\/\">on their blog<\/a>,\n<code>core_bench<\/code> is intended to measure the performance of small pieces of\nOCaml code. This library helps developers to better understand the\ncost of individual operations, like <code>map<\/code>.<\/p>\n<p>There are a couple benefits to measuring <code>map<\/code> implementations with\n<code>core_bench<\/code>.<\/p>\n<ol>\n<li>\n<p>The library makes it easy to track both time and use of the heap.<\/p>\n<\/li>\n<li>\n<p>Once you specify your test, <code>core_bench<\/code> automatically provides\n   many <a href=\"https:\/\/github.com\/janestreet\/core_bench\/wiki\/Getting-Started-with-Core_bench\">command line\n   options<\/a>\n   to help you present your test data in different ways.<\/p>\n<\/li>\n<li>\n<p>The library uses statistical techniques (bootstrapping and linear\n   regression) to reduce many runs worth of data to a small number of\n   meaningful performance metrics that account for the amortized cost\n   of garbage collection and error introduced by system activity.<\/p>\n<\/li>\n<\/ol>\n<p>I wrote\n<a href=\"https:\/\/github.com\/jsthomas\/ocaml-analysis\/blob\/master\/map\/maptest.ml\">this program<\/a>\nto compare performance between the six implementations I described\nabove. The program includes the batteries-hybrid I described above,\nwhich I'll refer to as <code>batt-hybr<\/code>. Other test details:<\/p>\n<ul>\n<li>I tested each algorithm against lists of lengths <span class=\"math\">\\(N=10^2, 10^3,\n  10^4\\)<\/span> and <span class=\"math\">\\(10^5\\)<\/span>. On my system, <span class=\"math\">\\(N=10^5\\)<\/span> was the highest power of 10\n  for which the <code>stdlib<\/code> implementation did not fail due to a stack\n  overflow.<\/li>\n<li>Each list consisted of integer elements (all 0), and the function\n  mapped onto the list simply added one to each element.<\/li>\n<li>I ran these tests on a Lenovo X220, Intel Core i5-2520M CPU (2.50GHz \u00d7\n  4 cores), with 4GB RAM.<\/li>\n<li>I used the OCaml 4.03.0 compiler, and compiled to native code\n  without using <code>flambda<\/code>. (<a href=\"https:\/\/github.com\/jsthomas\/ocaml-analysis\/blob\/master\/map\/makefile\">This\n  makefile<\/a>\n  gives the full specifications.)<\/li>\n<\/ul>\n<h1>Results<\/h1>\n<p>For each list size, <code>core_bench<\/code> produces a table with several metrics besides time:<\/p>\n<ul>\n<li><code>mWd<\/code> : Words allocated on the minor heap.<\/li>\n<li><code>mjWd<\/code> : Words allocated on the major heap.<\/li>\n<li><code>Prom<\/code> : Words promoted from minor to major heap.<\/li>\n<\/ul>\n<p>The library also allows us to produce 95% confidence intervals and\n<span class=\"math\">\\(R^2\\)<\/span> values for the time estimates.<\/p>\n<p><strong>Map Benchmark, N = 100<\/strong><\/p>\n<div class=\"highlight\"><pre><span><\/span><code>\u250c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u252c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u252c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u252c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u252c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u252c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u252c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u252c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2510\n\u2502 Name       \u2502 Time R^2 \u2502 Time\/Run \u2502          95ci \u2502 mWd\/Run \u2502 mjWd\/Run \u2502 Prom\/Run \u2502 Percentage \u2502\n\u251c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2524\n\u2502 ntr        \u2502     1.00 \u2502 741.20ns \u2502 -0.23% +0.22% \u2502 609.01w \u2502    0.53w \u2502    0.53w \u2502    100.00% \u2502\n\u2502 containers \u2502     1.00 \u2502 439.55ns \u2502 -0.64% +0.67% \u2502 304.03w \u2502    0.17w \u2502    0.17w \u2502     59.30% \u2502\n\u2502 batteries  \u2502     1.00 \u2502 581.65ns \u2502 -0.14% +0.16% \u2502 309.01w \u2502    0.35w \u2502    0.35w \u2502     78.47% \u2502\n\u2502 base       \u2502     1.00 \u2502 438.63ns \u2502 -0.19% +0.20% \u2502 304.03w \u2502    0.16w \u2502    0.16w \u2502     59.18% \u2502\n\u2502 stdlib     \u2502     1.00 \u2502 610.45ns \u2502 -0.10% +0.11% \u2502 304.01w \u2502    0.17w \u2502    0.17w \u2502     82.36% \u2502\n\u2502 batt-hybr  \u2502     1.00 \u2502 426.76ns \u2502 -0.15% +0.17% \u2502 304.03w \u2502    0.17w \u2502    0.17w \u2502     57.58% \u2502\n\u2514\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2534\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2534\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2534\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2534\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2534\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2534\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2534\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2518\n<\/code><\/pre><\/div>\n\n<p><strong>Map Benchmark, N = 1000<\/strong><\/p>\n<div class=\"highlight\"><pre><span><\/span><code>\u250c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u252c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u252c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u252c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u252c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u252c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u252c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u252c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2510\n\u2502 Name       \u2502 Time R^2 \u2502 Time\/Run \u2502          95ci \u2502 mWd\/Run \u2502 mjWd\/Run \u2502 Prom\/Run \u2502 Percentage \u2502\n\u251c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2524\n\u2502 ntr        \u2502     1.00 \u2502   8.84us \u2502 -0.14% +0.15% \u2502  6.01kw \u2502   52.08w \u2502   52.08w \u2502    100.00% \u2502\n\u2502 containers \u2502     1.00 \u2502   5.07us \u2502 -0.13% +0.15% \u2502  3.00kw \u2502   17.23w \u2502   17.23w \u2502     57.34% \u2502\n\u2502 batteries  \u2502     1.00 \u2502   6.57us \u2502 -0.14% +0.14% \u2502  3.01kw \u2502   34.71w \u2502   34.71w \u2502     74.32% \u2502\n\u2502 base       \u2502     1.00 \u2502   4.99us \u2502 -0.20% +0.24% \u2502  3.00kw \u2502   17.08w \u2502   17.08w \u2502     56.44% \u2502\n\u2502 stdlib     \u2502     1.00 \u2502   6.84us \u2502 -0.10% +0.10% \u2502  3.00kw \u2502   17.22w \u2502   17.22w \u2502     77.34% \u2502\n\u2502 batt-hybr  \u2502     1.00 \u2502   4.96us \u2502 -0.13% +0.13% \u2502  3.00kw \u2502   17.07w \u2502   17.07w \u2502     56.10% \u2502\n\u2514\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2534\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2534\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2534\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2534\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2534\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2534\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2534\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2518\n<\/code><\/pre><\/div>\n\n<p><strong>Map Benchmark, N = 10,000<\/strong><\/p>\n<div class=\"highlight\"><pre><span><\/span><code>\u250c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u252c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u252c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u252c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u252c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u252c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u252c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u252c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2510\n\u2502 Name       \u2502 Time R^2 \u2502 Time\/Run \u2502          95ci \u2502 mWd\/Run \u2502 mjWd\/Run \u2502 Prom\/Run \u2502 Percentage \u2502\n\u251c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2524\n\u2502 ntr        \u2502     0.99 \u2502 203.11us \u2502 -0.45% +0.53% \u2502 60.01kw \u2502   5.40kw \u2502   5.40kw \u2502    100.00% \u2502\n\u2502 containers \u2502     1.00 \u2502 144.95us \u2502 -0.50% +0.60% \u2502 48.01kw \u2502   3.04kw \u2502   3.04kw \u2502     71.37% \u2502\n\u2502 batteries  \u2502     1.00 \u2502 136.87us \u2502 -0.51% +0.63% \u2502 30.01kw \u2502   3.64kw \u2502   3.64kw \u2502     67.39% \u2502\n\u2502 base       \u2502     1.00 \u2502 130.85us \u2502 -0.34% +0.39% \u2502 44.98kw \u2502   2.66kw \u2502   2.66kw \u2502     64.42% \u2502\n\u2502 stdlib     \u2502     1.00 \u2502 118.70us \u2502 -0.30% +0.29% \u2502 30.00kw \u2502   1.80kw \u2502   1.80kw \u2502     58.44% \u2502\n\u2502 batt-hybr  \u2502     1.00 \u2502 106.91us \u2502 -0.42% +0.52% \u2502 30.01kw \u2502   2.22kw \u2502   2.22kw \u2502     52.64% \u2502\n\u2514\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2534\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2534\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2534\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2534\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2534\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2534\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2534\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2518\n<\/code><\/pre><\/div>\n\n<p><strong>Map Benchmark, N = 100,000<\/strong><\/p>\n<div class=\"highlight\"><pre><span><\/span><code>\u250c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u252c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u252c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u252c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u252c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u252c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u252c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u252c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2510\n\u2502 Name       \u2502 Time R^2 \u2502 Time\/Run \u2502          95ci \u2502  mWd\/Run \u2502 mjWd\/Run \u2502 Prom\/Run \u2502 Percentage \u2502\n\u251c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2524\n\u2502 ntr        \u2502     0.98 \u2502  10.27ms \u2502 -2.39% +2.32% \u2502 600.02kw \u2502 411.83kw \u2502 411.83kw \u2502     94.33% \u2502\n\u2502 containers \u2502     0.99 \u2502  10.62ms \u2502 -2.19% +1.83% \u2502 588.02kw \u2502 404.91kw \u2502 404.91kw \u2502     97.61% \u2502\n\u2502 batteries  \u2502     1.00 \u2502   7.19ms \u2502 -0.78% +0.79% \u2502 300.02kw \u2502 300.35kw \u2502 300.35kw \u2502     66.02% \u2502\n\u2502 base       \u2502     0.99 \u2502  10.88ms \u2502 -1.54% +1.41% \u2502 584.99kw \u2502 397.60kw \u2502 397.60kw \u2502    100.00% \u2502\n\u2502 stdlib     \u2502     0.99 \u2502   6.33ms \u2502 -1.08% +1.07% \u2502 300.01kw \u2502 171.73kw \u2502 171.73kw \u2502     58.18% \u2502\n\u2502 batt-hybr  \u2502     0.93 \u2502   6.09ms \u2502 -4.30% +4.63% \u2502 300.02kw \u2502 285.46kw \u2502 285.46kw \u2502     55.93% \u2502\n\u2514\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2534\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2534\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2534\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2534\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2534\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2534\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2534\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2518\n<\/code><\/pre><\/div>\n\n<p>A few things I noticed about the data:<\/p>\n<ul>\n<li>\n<p>The tail recursive implementation is slow, but not always the\n  slowest. In the <span class=\"math\">\\(N=10^5\\)<\/span> case, <code>ntr<\/code>,<code>base<\/code>, and <code>containers<\/code> show\n  similar performance; this makes sense given they have the same\n  behavior after a prefix of the list.<\/p>\n<\/li>\n<li>\n<p>For short lists, <code>base<\/code>, <code>containers<\/code>, and <code>batt-hybr<\/code> are fastest,\n  likely because of unrolling.<\/p>\n<\/li>\n<li>\n<p>We can see from the <code>mWd<\/code> and <code>mjWd<\/code> columns that <code>ntr<\/code> uses the\n  most heap space, as we would expect.<\/p>\n<\/li>\n<li>\n<p>As we increase the size of the list, <code>stdlib<\/code> gets faster relative\n  to <code>ntr<\/code>; I suspect this can be attributed to the cost of garbage\n  collection.<\/p>\n<\/li>\n<li>\n<p>Overall, <code>batt-hybr<\/code> appears to have the best performance (though in\n  the <span class=\"math\">\\(N=10^5\\)<\/span> case, the confidence interval is large enough that we\n  can't conclude <code>batt-hybr<\/code> is faster than <code>stdlib<\/code>, and the <span class=\"math\">\\(R^2\\)<\/span>\n  value is a bit low).<\/p>\n<\/li>\n<\/ul>\n<h1>Conclusions<\/h1>\n<p>The data above suggest three main findings:<\/p>\n<ol>\n<li>\n<p>The stack-based standard library implementation of <code>map<\/code> is faster\n   than the naive tail recursive implementation, taking about 60-80%\n   of the time to do the same work depending on the size of the list.<\/p>\n<\/li>\n<li>\n<p>There are clear benefits to both unrolling and\n   hybridizing. Hybridizing lets us take an implementation that\n   performs well on long lists (<code>batteries<\/code>), and make it even better\n   by combining it with one that's fast on short lists, to produce\n   <code>batt-hybr<\/code>.<\/p>\n<\/li>\n<li>\n<p>Overall, the data show we don't have to give up safety (resistance\n   to stack overflow) to get better performance. A tail recursive\n   implementation can be quite competitive, albeit more complex.<\/p>\n<\/li>\n<\/ol>\n<h1>Discussion<\/h1>\n<p>A follow up question to this analysis, in the context of the\ndiscussion of <code>Lwt_list.map_p<\/code> is: \"How significant is the cost of\n<code>map<\/code> compared to other operations?\" To partially address this, I\nwrote\n<a href=\"https:\/\/github.com\/jsthomas\/ocaml-analysis\/blob\/master\/map\/bufftest.ml\">another program<\/a>\nthat measures how long it takes to write 4096 bytes to a Unix pipe\nusing <code>Lwt_unix.write<\/code>, and then read it back using <code>Lwt_unix.read<\/code>. Using\n<code>core_bench<\/code>, I found:<\/p>\n<p><strong>Unix Pipe Read\/Write Benchmark<\/strong><\/p>\n<div class=\"highlight\"><pre><span><\/span><code>\u250c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u252c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u252c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u252c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u252c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2510\n\u2502Time R^2 \u2502 Time\/Run \u2502          95ci \u2502 mWd\/Run \u2502 Percentage \u2502\n\u251c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2524\n\u2502    1.00 \u2502 893.33ns \u2502 -0.16% +0.18% \u2502  56.00w \u2502    100.00% \u2502\n\u2514\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2534\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2534\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2534\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2534\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2518\n<\/code><\/pre><\/div>\n\n<p>It seems reasonable to estimate that <code>Lwt_list.map_p<\/code> would primarily\nbe applied to IO operations like the ones in this experiment. In that\ncase, the data suggest the cost per element of applying the slowest\n<code>map<\/code> implementation (<code>ntr<\/code>) is about 0.82% of the cost of one 4KB\nread\/write operation on a unix pipe. In the context of <code>Lwt<\/code>, it seems\nreasonable to conclude the implementation of <code>map<\/code> isn't a significant\nconcern; the real cost is performing IO. In light of that, it seems\npreferable to use an implementation that cannot cause a stack\noverflow.<\/p>\n<p>A second question that might be asked about this analysis is: \"Was it\nnecessary to introduce the added complexity of <code>core_bench<\/code> to measure\nthe performance of <code>map<\/code>?\" For example, one might set up a performance\ntest with just successive calls to <code>Time.now<\/code> or\n<code>Unix.gettimeofday<\/code>. In an earlier draft of this article, I tried such\nan\n<a href=\"https:\/\/github.com\/jsthomas\/ocaml-analysis\/blob\/master\/map\/profile.ml\">approach<\/a>,\nproducing some misleading data. In that test, I did a full garbage\ncollection in between runs (applications of <code>map<\/code>), which suppressed\nthat (nontrivial) cost and made the tail recursive implementation\nappear quite fast. <code>core_bench<\/code> does a much better job incorporating\nthe cost of garbage collection by varying the number of test runs\nperformed in a row and then establishing a trend (with linear\nregression) that reflects the amortized cost of garbage collection per\nrun.<\/p>\n<p>One interesting finding did arise from my earlier tests: for short\nlists, allocating memory on the heap actually appears to be faster\nthan creating frames on the stack. Since the tests perform a full\ngarbage collection between test runs, the timings show only the cost\nof allocating space on the heap. This produced data like the\nfollowing:<\/p>\n<p><strong>Summary Statistics, <span class=\"math\">\\(N=10^3\\)<\/span> Garbage Collected Map Benchmark Times (\u03bcs)<\/strong><\/p>\n<table class=\"dataframe\">\n  <thead>\n    <tr>\n      <th><\/th>\n      <th>Std. Lib.<\/th>\n      <th>NTR<\/th>\n      <th>Base<\/th>\n      <th>Batteries<\/th>\n      <th>Containers<\/th>\n    <\/tr>\n  <\/thead>\n  <tbody>\n    <tr>\n      <th>Mean<\/th>\n      <td>27.18<\/td>\n      <td>27.21<\/td>\n      <td>11.23<\/td>\n      <td>19.03<\/td>\n      <td>13.06<\/td>\n    <\/tr>\n    <tr>\n      <th>Min<\/th>\n      <td>15.97<\/td>\n      <td>14.07<\/td>\n      <td>6.91<\/td>\n      <td>9.06<\/td>\n      <td>7.87<\/td>\n    <\/tr>\n    <tr>\n      <th>25%<\/th>\n      <td>18.84<\/td>\n      <td>17.88<\/td>\n      <td>7.15<\/td>\n      <td>10.97<\/td>\n      <td>10.01<\/td>\n    <\/tr>\n    <tr>\n      <th>50%<\/th>\n      <td>20.03<\/td>\n      <td>19.07<\/td>\n      <td>8.11<\/td>\n      <td>15.50<\/td>\n      <td>10.01<\/td>\n    <\/tr>\n    <tr>\n      <th>75%<\/th>\n      <td>23.13<\/td>\n      <td>22.17<\/td>\n      <td>12.87<\/td>\n      <td>18.84<\/td>\n      <td>10.97<\/td>\n    <\/tr>\n    <tr>\n      <th>Max<\/th>\n      <td>849.01<\/td>\n      <td>576.02<\/td>\n      <td>379.80<\/td>\n      <td>622.03<\/td>\n      <td>434.88<\/td>\n    <\/tr>\n  <\/tbody>\n<\/table>\n\n<p><strong>Summary Statistics, <span class=\"math\">\\(N=10^4\\)<\/span> Garbage Collected Map Benchmark Times (\u03bcs)<\/strong><\/p>\n<table class=\"dataframe\">\n  <thead>\n    <tr>\n      <th><\/th>\n      <th>Std. Lib.<\/th>\n      <th>NTR<\/th>\n      <th>Base<\/th>\n      <th>Batteries<\/th>\n      <th>Containers<\/th>\n    <\/tr>\n  <\/thead>\n  <tbody>\n    <tr>\n      <th>Mean<\/th>\n      <td>230.23<\/td>\n      <td>216.60<\/td>\n      <td>141.39<\/td>\n      <td>144.59<\/td>\n      <td>161.56<\/td>\n    <\/tr>\n    <tr>\n      <th>Min<\/th>\n      <td>77.01<\/td>\n      <td>73.91<\/td>\n      <td>61.04<\/td>\n      <td>54.84<\/td>\n      <td>63.18<\/td>\n    <\/tr>\n    <tr>\n      <th>25%<\/th>\n      <td>97.04<\/td>\n      <td>86.07<\/td>\n      <td>67.95<\/td>\n      <td>58.89<\/td>\n      <td>70.81<\/td>\n    <\/tr>\n    <tr>\n      <th>50%<\/th>\n      <td>121.95<\/td>\n      <td>99.90<\/td>\n      <td>75.10<\/td>\n      <td>61.99<\/td>\n      <td>77.01<\/td>\n    <\/tr>\n    <tr>\n      <th>75%<\/th>\n      <td>193.83<\/td>\n      <td>284.91<\/td>\n      <td>148.59<\/td>\n      <td>118.26<\/td>\n      <td>175.24<\/td>\n    <\/tr>\n    <tr>\n      <th>Max<\/th>\n      <td>12719.87<\/td>\n      <td>2753.97<\/td>\n      <td>2960.21<\/td>\n      <td>3616.09<\/td>\n      <td>13603.93<\/td>\n    <\/tr>\n  <\/tbody>\n<\/table>\n\n<p>When we ignore the time spent on garbage collection, we see that <code>ntr<\/code>\nis surprisingly competitive, especially in comparison with <code>stdlib<\/code>;\nthe difference between the two implementations, of course, is that\n<code>ntr<\/code> allocates more memory on the heap while <code>stdlib<\/code> creates more\nstack frames.<\/p>\n<h2>Notes<\/h2>\n<p>Thanks to <a href=\"https:\/\/github.com\/aantron\">Anton Bachin<\/a> and\n<a href=\"https:\/\/github.com\/c-cube\/\">Simon Cruanes<\/a> for reading drafts of this\npost.<\/p>\n<script type=\"text\/javascript\">if (!document.getElementById('mathjaxscript_pelican_#%@#$@#')) {\n    var align = \"center\",\n        indent = \"0em\",\n        linebreak = \"false\";\n\n    if (false) {\n        align = (screen.width < 768) ? \"left\" : align;\n        indent = (screen.width < 768) ? \"0em\" : indent;\n        linebreak = (screen.width < 768) ? 'true' : linebreak;\n    }\n\n    var mathjaxscript = document.createElement('script');\n    mathjaxscript.id = 'mathjaxscript_pelican_#%@#$@#';\n    mathjaxscript.type = 'text\/javascript';\n    mathjaxscript.src = 'https:\/\/cdnjs.cloudflare.com\/ajax\/libs\/mathjax\/2.7.3\/latest.js?config=TeX-AMS-MML_HTMLorMML';\n\n    var configscript = document.createElement('script');\n    configscript.type = 'text\/x-mathjax-config';\n    configscript[(window.opera ? \"innerHTML\" : \"text\")] =\n        \"MathJax.Hub.Config({\" +\n        \"    config: ['MMLorHTML.js'],\" +\n        \"    TeX: { extensions: ['AMSmath.js','AMSsymbols.js','noErrors.js','noUndefined.js'], equationNumbers: { autoNumber: 'none' } },\" +\n        \"    jax: ['input\/TeX','input\/MathML','output\/HTML-CSS'],\" +\n        \"    extensions: ['tex2jax.js','mml2jax.js','MathMenu.js','MathZoom.js'],\" +\n        \"    displayAlign: '\"+ align +\"',\" +\n        \"    displayIndent: '\"+ indent +\"',\" +\n        \"    showMathMenu: true,\" +\n        \"    messageStyle: 'normal',\" +\n        \"    tex2jax: { \" +\n        \"        inlineMath: [ ['\\\\\\\\(','\\\\\\\\)'] ], \" +\n        \"        displayMath: [ ['$$','$$'] ],\" +\n        \"        processEscapes: true,\" +\n        \"        preview: 'TeX',\" +\n        \"    }, \" +\n        \"    'HTML-CSS': { \" +\n        \"        availableFonts: ['STIX', 'TeX'],\" +\n        \"        preferredFont: 'STIX',\" +\n        \"        styles: { '.MathJax_Display, .MathJax .mo, .MathJax .mi, .MathJax .mn': {color: 'inherit ! important'} },\" +\n        \"        linebreaks: { automatic: \"+ linebreak +\", width: '90% container' },\" +\n        \"    }, \" +\n        \"}); \" +\n        \"if ('default' !== 'default') {\" +\n            \"MathJax.Hub.Register.StartupHook('HTML-CSS Jax Ready',function () {\" +\n                \"var VARIANT = MathJax.OutputJax['HTML-CSS'].FONTDATA.VARIANT;\" +\n                \"VARIANT['normal'].fonts.unshift('MathJax_default');\" +\n                \"VARIANT['bold'].fonts.unshift('MathJax_default-bold');\" +\n                \"VARIANT['italic'].fonts.unshift('MathJax_default-italic');\" +\n                \"VARIANT['-tex-mathit'].fonts.unshift('MathJax_default-italic');\" +\n            \"});\" +\n            \"MathJax.Hub.Register.StartupHook('SVG Jax Ready',function () {\" +\n                \"var VARIANT = MathJax.OutputJax.SVG.FONTDATA.VARIANT;\" +\n                \"VARIANT['normal'].fonts.unshift('MathJax_default');\" +\n                \"VARIANT['bold'].fonts.unshift('MathJax_default-bold');\" +\n                \"VARIANT['italic'].fonts.unshift('MathJax_default-italic');\" +\n                \"VARIANT['-tex-mathit'].fonts.unshift('MathJax_default-italic');\" +\n            \"});\" +\n        \"}\";\n\n    (document.body || document.getElementsByTagName('head')[0]).appendChild(configscript);\n    (document.body || document.getElementsByTagName('head')[0]).appendChild(mathjaxscript);\n}\n<\/script>","category":{"@attributes":{"term":"OCaml"}}}]}