Personal tools

Haskell Quiz/Bytecode Compiler

From HaskellWiki

< Haskell Quiz
Revision as of 15:17, 7 November 2006 by Mgsloan (Talk | contribs)

Jump to: navigation, search

1 The Problem

Create a bytecode compiler as described on this ruby quiz page: http://www.rubyquiz.com/quiz100.html

Use this tester by Michael Sloan:

fromBytes n = foldl (\c (i, n) -> c + n * 2^(i*8) ) 0 . zip [(n-1),(n-2)..0]
 
interpret [] [] = error "no result produced"
interpret (s1:s) [] = s1
interpret s (o:xs) | o < 10 = interpret ((fromBytes (o*2) xs):s) (drop (o*2) xs)
interpret (s1:s2:s) (o:xs)
  | o == 16 = interpret (s2:s1:s) xs
  | otherwise = interpret (((case o of 10 -> (+); 11 -> (-); 12 -> (*); 13 -> (^); 14 -> div; 15 -> mod) s2 s1):s) xs
 
test :: (String -> [Int]) -> IO ()
test f = assert "2+5" 7 >> assert "2-1" 1 >> assert "2*12" 24 >> assert "2^3" 8 >> assert "5/2" 2 >> assert "15%4" 3 >>
         assert "2+2+2" 6 >> assert "2^8/4" 64 >> assert "3*11%3" 6 >>
         assert "2*(3+4)" 14 >> assert "(3/3)+(8-2)" 7 >> assert "(1+3)/(2/2)*(10-8)" 8 >> assert "(10%3)*(2+2)" 4 >>
         assert "(10/(2+3)*4)" 8 >> assert "5+((5*4)%(2+1))" 7 >> assert "-(2-3-5)" 10 
  where assert str val = print ((if (interpret [] $ f str) == val then "Passed: " else "Failed: ") ++ str)

2 Solutions