oleg | 12 Jun 17:27 2014

Simple but slow, and complex but fast Forth emulation [Was: Bang, a drum DSL for Haskell]

Emulation of a simple subset of Forth in Haskell seems easy. The trick,
continuation-passing style, has been known for a long time. The trick
underlies `functional unparsing' by Olivier Danvy.
(published in JFP in 1998). 

Chris Okasaki later extended the technique

He also noted huge types and slow compilation times.

But there is another way. It is far more complex, and far fast. It is
used in HSXML, which handles polyvariadic functions with literally
thousands of arguments (some of my web pages are long). The following
complete code illustrates the idea.

{-# LANGUAGE MultiParamTypeClasses #-}
{-# LANGUAGE FlexibleInstances, FlexibleContexts #-}
{-# LANGUAGE TypeFamilies #-}

-- Simple Forth

module SimpleForth where

-- The simple way: Danvy's Functional unparsing
begin k = k ()
n st x k = k ((x::Int),st)
add (n1,(n2,st)) k = k (n1+n2,st)
(Continue reading)