Thursday, November 5, 2020

Hello Server: Haskell + Elm Across Data Boundaries

 I started with the thought that it would be fun to write a small, private social network app in Elm, for family and friends to share. This immediately begs the question: what should the backend be? 

Setting aside for the moment the class of problems associated with running infrastructure with real users and data on the internet (e.g. security, availability, load, etc), there is the problem of type consistency and safety.

Maintaining safe, static data typing across data boundaries (say, client and server, or server and persistence layer) seems inherently tricky. Ideally, one wants to define data types (or data structures) somewhere,  exactly once, and have some abstractions and / or tools that propagate the type guarantees throughout the stack. That would safe effort, minimize boilerplate, and prevent typ(e)o-related errors!

The Elm ecosystem actually has Lamdera, whose the promise is that the server and persistence layers are abstracted away, leaving the developer to reason only about Elm data structures and what data maintain logically in the front vs back end. That's pretty much exactly what I want in this instance! Sadly, it remains in alpha, and doesn't appear to be open source for the moment.

Browsing through the State of the Haskell ecosystem, there are a variety of options for running servers and handling persistence in Haskell (the most obvious fit with Elm). Some of them look like they need project status updates (like Spock... people want to know the status, as it's been dormant for ~three years!). But of course I'm not the first to encounter this problem... so there are a few promising libraries. 


Haskell Server + Elm code gen + no persistence

The first is servant-elm, which wraps the elm-bridge library for use with the Servant webserver. 

Following Servant's tutorial and the servant-elm README on Github, we can:  

  1. Define ADTs of our choice in Haskell, with corresponding typed REST APIs for Servant
  2. auto-generate Elm code for corresponding data, including JSON serializers / deserializers that match the REST API (!)
This file defines the Haskell ADTs and API endpoints, with the Template Haskell line that servant-elm needs: deriveBoth defaultOptions ''ServerState

This file then defines the server logic, with an IORef to maintain some simple in-memory state.

Finally, this file actually generates the Elm module (well, the binary that generates the Elm module).

The resulting Elm code works as expected, albeit with some long function names!

To actually use the Elm client with localhost, I needed to start a temporary version of Chrome with some web security options disabled to account for CORS (borrowed from here).


Next post... adding persistence.





Monday, November 2, 2020

Parser Combinator for SQL Subset

Some more records from RC... a fellow Recurser and I presented on our toy SQL parser combinator at the Friday 5-minute talks (talk slides).

We actually ended up writing parser combinators from scratch twice during RC (first for CIS194 and again for fp-course). The two had almost identical primitives like satisfy :: (Char -> Bool) -> Parser Char, zeroOrMore, oneOrMore, and building up from there... which makes me wonder if there's just a standard recipe for parser combinators? 

For the toy SQL parser, we ended up referencing how Stephen Diehl uses Parsec in Kaleidescope once we defined the syntax. It turns our that Parsec provides a bunch of primitives we previously wrote ourselves, like brackets, parens, commaSep... But I think it would have taken us much longer to figure out how to use the package, were it not for Diehl's examples.

https://github.com/tkuriyama/toydb/blob/master/src/Database/Parser.hs


*Database.Parser> process "Insert Into myTable [1, True, \"Jonathan\"];"

Insert "myTable" [FvInt 1,FvBool True,FvText "Jonathan"]


*Database.Parser> process "Insert Into myTable [1, True, \"Jonathan\"]"

(line 1, column 42):

unexpected end of input

expecting ";"


*Database.Parser> process "Insert myTable [1, True];"

(line 1, column 8):

unexpected "m"

expecting "Into"


12 Weeks of RC

 Summary of my 12 weeks at Recurse Center (https://www.recurse.com/).


It was, unequivocally, a fun and intellectually rewarding experience that I'd recommend to folks interested in programming -- at pretty much any stage of life or career. It's free to attend, for the moment virtual, and available in 1, 6, and 12 week formats).


  • Organized a daily study group for functional programming (mainly Haskell)
  • Attended weekly study groups for systems programming and type theory
  • Learned about Elm and wrote some visualizations (sudoku, risk)
  • Learned about networking primitives and wrote some buggy toy servers
  • Contributed to a friend's Haskell game (networked and concurrent!), soon to be internet-playable
  • Spent some time with property-based testing, test coverage, and TCR == (Test && Commit) || Revert
  • Procrastinated on writing computer-generated music (small example sonifying the Collatz sequence)
  • Started a group project to write a toy database in Haskell (with a toy SQL parser combinator and B-Trees)
  • Attended 6-12 technical and non-technical a week (most of them 5 mins); gave five 5-min talks
  • Attended a great talk on Turing's '36 paper on computation; presented on Dijkstra's '74 essay on scientific thought
  • Wrote a few thousand lines of code -- the below table is an inaccurate though representative summary (using tokei)
===============================================================================
 Language            Files        Lines         Code     Comments       Blanks
===============================================================================
 C                       8         1169          935           31          203
 C Header                1          229           64          122           43
 Elm                    12         1322         1061           43          218
 Haskell                49         5231         2232         2327          672
 Org                     3          236          155            0           81
 Python                  9          743          585           23          135
 Shell                   6           16           13            1            2
 Zig                     3           56           41            0           15
 Zsh                     1           26           20            1            5
-------------------------------------------------------------------------------
 Jupyter Notebooks       4            0            0            0            0
 |- Markdown             4          191            0          134           57
 |- Python               4          722          623           21           78
 (Total)                            913          623          155          135
===============================================================================
 Total                  96         9941         5729         2703         1509
===============================================================================

Tuesday, October 20, 2020

Network Programming

We decided to a bit of socket-level network programming as part of the systems programming study group at Recurse Center. The canonical text would appear to be the Unix Network Programming book, but Beej's guide also came highly recommended -- with the added benefit of being quicker to get started and freely available online: 
It turns out that following the correct order of syscalls per Beej's incantations is relatively straightforward... yielding very simple toy servers in short order:
On the other hand, some fundamentals of C programming still elude me, e.g. I couldn't work out how to refactor the creation of sockets into a standalone function due to some (presumably basic) pointer issues...

Monday, October 19, 2020

fp-course

Following the Learn Haskell recommendation, the FP study group at Recurse Center  worked through the fp-course exercises after finishing CIS 194. 

https://github.com/bitemyapp/learnhaskell

The exercises seem to provide good practice, with modules like State and StateT requiring some mental gymnastics training..! 

The repo unfortunately has some incomplete tests files, so I transcribed a few from the comments into HSpec format for Parser.hs and MoreParser.hs: https://github.com/tkuriyama/puzzles/tree/master/fp-course. 

The test cases were tedious but turned out to be worthwhile, since JsonParser.hs is comprised of more abstract parser combinators. (Interestingly, the parser combinator in CIS 194 is almost identical to fp-course in its building blocks... a coincidence, or a common design pattern?).

Anagrams and Cheque remain to be completed, but we're moving on to writing a toy database in Haskell (with the goal to complete in the last two weeks of the Fall 1 batch!).


Sunday, October 11, 2020

Game of Risk Elm Visualization

Building on the previous post... an interactive(ish) Elm visualization of the game's probability trees: 

https://tarokuriyama.com/projects/risk.php