HiveBrain v1.2.0
Get Started
← Back to all entries
patternMinor

A stack-based language interpreter in Haskell

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
interpreterstacklanguagebasedhaskell

Problem

Here is a little interpreter I wrote for a simple stack-based language. It is my first attempt at a complete Haskell program, beyond glorified calculator use.

I'd like very much to get an expert's opinon on stylistic matters.

Also, although the thing runs fine, on a test program it seems to suffer from a space leak: I see an increasing amount of Map objects in Drag state, at one particular spot in the code (where the SCC "store1" directive is). I don't understand why the insert step would not free the old Map version. Also, retainer profiling blames the "arry" lens, which is not even used in this piece of code, and uses an IntMap, not a Map. I don't understand what is going on...

EDIT: whoops. I was using the sieve of Eratosthenes as a test program for my interpreter, so it is probably normal that the IntMap usage grows linearily in time..

{-# LANGUAGE NoMonomorphismRestriction #-}
{-# LANGUAGE TemplateHaskell #-}

module Mango where

import Control.Applicative ((), (), (> return ()

-- Lens for array items
item :: Integer -> Lens (IntMap v) v
item idx = lens (IM.! (fromInteger idx)) (IM.insert (fromInteger idx))

----------
-- PARSING

type ProgPtr = [Tok]
data Tok = Label String
| Number Integer
| Keyword String
deriving Show

comment = (string "/*" >> in_comment) "comment"
voidChar = () > return ())
((comment voidChar) >> in_comment)
"end of comment"

whitespace = many1 (() comment )

tchar = oneOf $ '_' : ['a'..'z']

tok = Number . read many1 digit
do
ident > return (Label ident))
return (Keyword ident)
"token"

-- eof here chokes on trailing garbage, but prevents single-pass parsing
program = optional whitespace >> (tok
sepEndBy1` whitespace) " ++ show v

instance Show Value where
show (IntVal n) = show n
show (PtrVal _) = ""

data ProgState = ProgState {
_stack :: [Stack],
_vars :: Map String Value,
_arry :: IntMap Value,
_ip

Solution


  • Name of Stack type is misleading, you mean Stack element


(StackElt), not a whole stack.

  • Same for withErrors. withX is


usually reserved for two or more argument function, such that the
last argument is function taking argument of typeX, e.g. \x :: X
-> ...
Did you mean handleErrors?

  • Did you really mean that value of an error is an error message? Or did you



rather intend to display
error and go on with execution? (This is not clear from code. One
should insert comment whenever intention of code is not apparent, or
just complicated.)

  • Did you use hlint on this code?

Context

StackExchange Code Review Q#18981, answer score: 6

Revisions (0)

No revisions yet.