Execute HQ9+: Difference between revisions

Line 243:
===Standard approach===
 
<lang ela>open Consoleconsole char cell imperative
open Char
open Cell
open Imperative
 
let eval src = eval' src
where eval' [] = ()
eval' (x::xs) | be 'H' = h! $ eval' xs
Line 255 ⟶ 252:
| be '+' = p! $ eval' xs
| else = fail ("Unrecognized " ++ x)
where refr = cellref 0
et be c = upper x == c
et h () = writen "Hello, world!"
et q () = writen src
et p () = mutate (valueof ref r.+ 1) ref
et n () = bottles [99,98..1]
where bottles [] = ()
bottles (x::xs) = rec write
Line 272 ⟶ 269:
An interpreter itself has no side effects:
 
<lang ela>open Consolelist char
open Core
open Char
let eval src = eval' src 0
where eval' [] a = []
eval' (x::xs) a | be 'H' = h :: eval' xs a
Line 282 ⟶ 277:
| be '9' = force n :: eval' xs a
| be '+' = eval' xs (a+1)
| else = fail "Invalid instruction."
where be c = upper x == c
et h = "Hello, world!"
et q = src
et n = (& bottles [99,98..1])
where bottles [] = ""
bottles (x::xs) =
show x ++ " bottles of beer of the wall\r\n"
++ show x ++ " bottles of beer\r\n"
++ "Take one down, pass it around\r\n"
++ bottles xs</lang>
 
It slightly alters an original HQ9+ specification. HQ9+ is an impure language that does console output. However console output is the only interaction that a user can see when executing HQ9+ program. This interpreter doesn't output to console but instead generates a list with all outputs. An accumulator is moved to the interpter arguments and the need for a reference cell is eliminated. Once an interpreter completes a client code can output to console like so:
 
<lang ela>eachopen writen <| eval "HQ9+"</lang>console
each writen <| eval "HQ9+"</lang>
 
=={{header|Erlang}}==
Anonymous user