Hacker Newsnew | comments | show | ask | jobs | submit login

Amusingly, just like whoever wrote the Haskell example linked in the blog, the very first thing I did with free monads was also write a trivial stack-based language. All I supported was pushing numbers to the stack and addition. Not a very complicated language! Programs look something like:

    prog = do {1; 2; add; 3; 4; add; add}
The cool thing is that I get "subroutines" (or, as Forth calls them, "words") for free:

    incr = do {1; add}
    prog = do {1; incr; incr; incr}
The interesting thing is that incr and prog are actually ASTs: I can run them, with a function called runProgram, but I can just as easily pretty print them. This is a wonderful property of free monads that's very useful for real DSLs. And, in fact, I'm using them for a current project--they're great.

With a bit of cleverness, it's probably possible to encode some of the stack semantics into the type system, making running a program with too few or too many elements left on the stack a type error. Also, with GADTs, I can probably add support for something like strings and have a mini string/int type system just for my little language, without much effort.




> it's probably possible to encode some of the stack semantics into the type system, making running a program with too few or too many elements left on the stack a type error

Indeed, Factor does this. In addition to checking for stack (over/under)-flows it's what allows really powerful behavior like the ability to say "run both these words with the current stack" without having to explicitly state how much of the stack to duplicate.

-----


I’m working on a statically typed concatenative language and would be happy to chat about typing in your stack language. My username at Gmail.

-----




Guidelines | FAQ | Support | API | Security | Lists | Bookmarklet | DMCA | Apply to YC | Contact

Search: