Your job is to create a simple interpreter for a simple golfing language.


Input will be in the form of string separated by spaces.

You can replace space separation with what you want


Output the result (a number or a string) obtained after performing all operations. If there are more than one output join the together to give a single result (no separators). The variable's initial value is always zero. i.e: It start at 0

Language Syntax :

The language has following operators :

inc  ---> add one to variable
dec  ---> remove one from variable
mult ---> multiply variable by 2
half ---> divide the variable by 2
Pri  ---> print the variable to console (or whatever your language has)
exit ---> end the program (anything after this is ignored)


inc inc inc dec Pri exit                 ---> 2
dec inc mult inc inc Pri                 ---> 2
inc inc inc mult half Pri exit inc       ---> 3
inc Pri inc Pri inc Pri exit half mult   ---> 123
Pri exit                                 ---> 0
inc half Pri exit                        ---> 0.5 


This is code-golf so shortest code in bytes for each language will win.


  • Input will always be valid . (string of operators separated with space)
  • You can round down to nearest integer if you don't want decimal places.
  • 3
    \$\begingroup\$ Can I take a list of strings? Can I use another capitalization? \$\endgroup\$ – user202729 Apr 27 '18 at 10:02
  • \$\begingroup\$ Add exit case? exit should matter \$\endgroup\$ – l4m2 Apr 27 '18 at 12:01
  • 1
    \$\begingroup\$ @Kaldo : You can separate using new lines \$\endgroup\$ – Muhammad Salman Apr 27 '18 at 15:00
  • 3
    \$\begingroup\$ Hmm, I wouldn't call that language "golfing language". \$\endgroup\$ – Paŭlo Ebermann Apr 28 '18 at 11:49
  • 1
    \$\begingroup\$ This is Deadfish with double and half instead of square and longer command names \$\endgroup\$ – Jo King Apr 30 '18 at 3:42

26 Answers 26


Bash, 61 bytes

sed '1i0

Try it online!

Converts the program into a dc program, then evaluates it as dc code. This takes the input separated by newlines. Note that dc is stack-based and uses reverse polish notation.

The input is first piped to sed

1i0 on the first line of input, insert (prepend) a 0, this will be the accumulator

s/.//2g remove everything but the first character on each line

y"idmhe"+-*/q" transliterate idmhe into +-*/q respectively, + - * / are the arithmetic commands and q quits the program

/+\|-/ on every line containing + or -, i1 insert a 1

/*\|\// on every line containing * or /, i2 insert a 2

/P/ on every line containing P, cdn change it into dn, equivalent to duplicate and output without newline in dc

Now this is evaluated as a dc expression.

  • 2
    \$\begingroup\$ I suppose it's not unreasonable to expect sed syntax to become even more alien than previously thought possible when golfing comes into play. \$\endgroup\$ – Mateen Ulhaq Apr 28 '18 at 11:48

Jelly, 21 bytes


Try it online!

Note that the ASCII values of the first characters (idmhPe) modulo 11 are unique modulo 6.

Using modulo 16:

Jelly, 21 bytes


Try it online!

The string that is used to index into is ḤH‘’IȮ in this case. The ‘’ are no longer on the boundaries.

  • \$\begingroup\$ Using 11 bytes to represent a 6-byte string is... too bad. But... “” takes 2 bytes, ¤ takes 1 byte, the data itself takes 6 bytes, there are 2 bytes left to do something. Currently it's and j, but ịØJ or ṃØJ is much worse, and doesn't work (because Unicode). \$\endgroup\$ – user202729 Apr 27 '18 at 11:46
  • \$\begingroup\$ jli's string concept ("A string is a list of integers with a special flag to affect printing") is great. \$\endgroup\$ – user202729 Apr 27 '18 at 11:52

R, 128 125 bytes

Reduce(function(x,y)switch(y,i=x+1,d=x-1,m=x*2,h=x/2,P={cat(x);x}),substr(el(strsplit(gsub("e.*$","",scan(,""))," ")),1,1),0)

Try it online!

Must be called with source(echo=FALSE) to prevent the return value from being printed automatically. The alternative would be to wrap everything in invisible but that's much less golfy (and ruins my [still] nice byte count).


05AB1E, 25 bytes


Try it online!

Maps each of the language function with the corresponding 05AB1E function (using the first char of each function), and then executes the resulting string as 05AB1E code.


Red, 121 bytes

func[s][v: 0 parse s[any[["i"(v: v + 1)|"d"(v: v - 1)|"m"(v: v * 2)|"h"(v: v / 2.0)|"P"(prin v)|"e"(exit)]thru" "| end]]]

Try it online!


f: func [s] [
    v: 0
    parse s [
        any [
            [ "i" (v: v + 1)
            | "d" (v: v - 1)
            | "m" (v: v * 2)
            | "h" (v: v / 2.0)
            | "P" (prin v)
            | "e" (exit)]
            thru [" " | end]

Python 2, 131 125 122 121 118 117 115 bytes

for x in input().split("x")[0].split():
print o

Try it online!

-6 and -3 with thanks to @Rod

-3 and -2 with thanks to @etene

-1 by replacing "Pri"==x with "P"in x

  • \$\begingroup\$ you can split on "exit" and get the 1st block, instead breaking saving 4 bytes \$\endgroup\$ – Rod Apr 27 '18 at 12:16
  • 1
    \$\begingroup\$ You can remove the parentheses around 'idmh' and use find instead of index, that will save a few bytes \$\endgroup\$ – etene Apr 27 '18 at 12:19
  • \$\begingroup\$ @Rod - can actually take that a bit further and split on exto save another 2 \$\endgroup\$ – ElPedro Apr 27 '18 at 12:25
  • \$\begingroup\$ You can replace v=(v+1,v-1,v*2,v/2.) with v+=(1,-1,v,-v/2.) it should work, didn't tested though \$\endgroup\$ – Rod Apr 27 '18 at 12:29
  • \$\begingroup\$ @Rod - thought about that but couldn't work out how to do the half. So simple! Thanks. \$\endgroup\$ – ElPedro Apr 27 '18 at 12:44

Python 3, 110 91 82 bytes

exit will cause the program to exit with an error.

for c in input():c=='P'==print(x,end='');x+=(1,-1,x,-x/2,c,0)['ndmhx'.find(c)]

Try it online!

  • \$\begingroup\$ Shorten your variable names to save 9 bytes. i='x+=1';d='x-=1';... and then in your exec call, change it to exec(eval(c[0])) \$\endgroup\$ – mypetlion Apr 27 '18 at 16:33
  • \$\begingroup\$ @mypetlion Thanks, but I found a better way. \$\endgroup\$ – mbomb007 Apr 27 '18 at 16:35
  • \$\begingroup\$ I think this is valid: 82 bytes \$\endgroup\$ – Lynn Apr 27 '18 at 22:52
  • \$\begingroup\$ @Lynn That's great! I couldn't think of a nice way to short-circuit to the print statement! \$\endgroup\$ – mbomb007 Apr 28 '18 at 1:00

JavaScript (ES6), 83 79 bytes

Saved 4 bytes thanks to @l4m2

Iteratively replaces the instructions with either the output or empty strings.


Try it online!


s =>                       // given the input string s
  s.replace(/\S+./g, w =>  // for each word w in s:
    m < s ?                //   if m is a string:
      ''                   //     ignore this instruction
    :                      //   else:
      w < {} ?             //     if w is 'Pri' ({} is coerced to '[object Object]'):
        m                  //       output the current value of m
      : (                  //     else:
          m +=             //       add to m:
            { d: -1,       //         -1 if w is 'dec'
              e: w,        //         w  if w is 'exit' (which turns m into a string)
              i: 1,        //         1  if w is 'inc'
              m            //         m  if w is 'mult'
            }[w[0]]        //       using the first character of w to decide
            || -m / 2,     //       or add -m/2 (for 'half') if the above result was falsy
        ''),               //       do not output anything
    m = 0                  //   m = unique register of our mighty CPU, initialized to 0
  )                        // end of replace()
  • \$\begingroup\$ s=>s.replace(/\S+./g,w=>k<s?'':w<{}?k:(k+={d:-1,e:w,i:1,m:k}[w[0]]||-k/2,''),k=0) \$\endgroup\$ – l4m2 Apr 28 '18 at 5:36
  • \$\begingroup\$ @l4m2 This w<{} is pure evil :p \$\endgroup\$ – Arnauld Apr 28 '18 at 5:46
  • \$\begingroup\$ s=>s.replace(/\S+./g,e=>m<s?'':e<{}?m:(m+={d:-1,e,i:1,m}[e[0]]||-m/2,''),m=0) also work \$\endgroup\$ – l4m2 Apr 28 '18 at 5:52

Charcoal, 37 35 bytes


Try it online! Link is to verbose version of code. Inspired by @RickHitchcock's answer. Explanation:


Clear the variable.


Truncate the input at the x if there is one, then loop over and switch on each character of (the remainder of) the input.


n increments the variable.


d decrements the variable.


m multiplies the variable by two (i.e. doubles).


h halves the variable.


r prints the variable cast to string.

  • 1
    \$\begingroup\$ @RickHitchcock Sorry, didn't test that thoroughly enough. I found a workaround but it cost me a byte. \$\endgroup\$ – Neil Apr 27 '18 at 19:26

JavaScript (ES6), 77 75 bytes

(Borrowed (stole) @Arnauld's trick of using m as the variable name, saving 2 bytes.)


Recursively walks the string, looking for distinct letters per instruction and ignoring the rest:

  • n: inc
  • d: dec
  • m: mult
  • h: half
  • P: Pri
  • x: exit

Takes advantage of the fact that undefined is neither greater than nor less than 'x', causing the recursion to stop at the end of the string or when it encounters the 'x' in exit.


console.log(f('inc inc inc dec Pri exit'));                 //--> 2
console.log(f('dec inc mult inc inc Pri'));                 //--> 2
console.log(f('inc inc inc mult half Pri exit inc'));       //--> 3
console.log(f('inc Pri inc Pri inc Pri exit half mult'));   //--> 123
console.log(f('Pri exit'));                                 //--> 0
console.log(f('inc half Pri exit'));                        //--> 0.5 

  • 1
    \$\begingroup\$ Following up to your deleted comment to which I can of course no longer reply, I forgot to paste in the link to the corrected code (d'oh!) but I found a new approach that's 2 bytes shorter than my original attempt anyway. \$\endgroup\$ – Neil Apr 30 '18 at 0:01

JavaScript (Node.js), 107 bytes

f=s=>s.split` `.map(([o])=>F?0:o=="i"?i++:o=="d"?i--:o=="m"?i*=2:o=="h"?i/=2:o=="P"?S+=i:F=1,F=i=0,S="")&&S

Try it online!

  • \$\begingroup\$ Shaved off two bytes \$\endgroup\$ – user79855 Apr 27 '18 at 11:06
  • \$\begingroup\$ This as it is should be counted as 105 bytes afaik, as long as your function doesn't call itself you don't need to count f= \$\endgroup\$ – Brian H. Apr 27 '18 at 11:56

JavaScript (Node.js), 91 bytes

_=>_.split` `.map(o=>o<{}>!_?S+=+i:o<"e"?i--:o<"f"?++_:o<"i"?i/=2:o<"j"?i++:i*=2,i=S="")&&S

Try it online!

JavaScript (Node.js), 96 bytes

_=>_.split` `.map(o=>F?0:o<"Q"?S+=i:o<"e"?i--:o<"f"?F=1:o<"i"?i/=2:o<"j"?i++:i*=2,F=i=0,S="")&&S

Try it online!

JavaScript (Node.js), 99 bytes

s=>s.split` `.map(_=>eval('++i7--i7++e7u+=+i7i*=27i/=2'.split(7)[Buffer(e+_)[0]%11%6]),e=i=u='')&&u

Try it online!


JavaScript, 107 bytes

s=>eval('x=0;x'+(s.split` `.map(v=>({i:"++",d:"--",m:"*=2",h:"/=2",P:";alert(x)",e:"//"})[v[0]]).join`;x`))

Haskell, 93 bytes

a!(c:t)|c=='P'=show a++a!t|c>'w'=""|1<2=(a+sum(lookup c$zip"ndmh"[1,-1,a,-a/2]))!t;a!e=e

Try it online!

Essentially a translation of mbomb007's Python answer.


Lua, 207 bytes

s=0;n=0;for a in io.read():gmatch'.'do if s==0 then s=1;n=a=='i'and n+1 or a=='d'and n-1 or a=='m'and n*2 or a=='h'and n/2 or n;if a=='P'then print(n)elseif a=="e"then break end elseif a==' 'then s=0 end end

Python 3, 114 110 109 116 bytes

Actually would have taken two bytes less in Python 2 because exec is a statement and doesn't need parentheses...

  • Saved 4 extra bytes thanks to @ElPedro

  • Saved an extra byte by taking advantage of the fact that find returns -1 on error, which can then be used as an index

  • +7 bytes because I hadn't noticed the no-newlines rule :(

i=0;exec(";".join("i+=1 i-=1 i*=2 i/=2 print(i,end='') exit()".split()["idmhP".find(h[0])]for h in input().split()))

Try it online!

Maps the first character of every input word to a piece of Python code. These are then concatenated and execed.

Pretty straightforward approach, that could probably be golfed a bit more. The difficulty mostly resides in finding the shortest form out of many possible ones...

  • \$\begingroup\$ 112 Try it online! if you have the commands as a space seperated string and split it. \$\endgroup\$ – ElPedro Apr 27 '18 at 13:13
  • 1
    \$\begingroup\$ 110 in fact as the brackets can go Try it online! \$\endgroup\$ – ElPedro Apr 27 '18 at 13:31
  • \$\begingroup\$ This doesn't give the correct output. The question says you must print without separators, so you need print(i,end=''). See the 4th test case. \$\endgroup\$ – mbomb007 Apr 27 '18 at 15:52
  • \$\begingroup\$ I hadn't noticed, I'll fix it. Thanks ! \$\endgroup\$ – etene Apr 27 '18 at 16:05
  • \$\begingroup\$ @etene Comment when you've fixed it and I'll remove my downvote. \$\endgroup\$ – mbomb007 Apr 28 '18 at 1:03

Ruby + -na, 81 73 65 bytes

x=0;$F.map{|w|eval %w{x+=1 x-=1 1/0 $><<x x*=2 x/=2}[w.ord%11%6]}

Try it online!

Pretty straightforward. For the first letter of each word, find the corresponding command string and eval it. Uses integer division, and exits by throwing a ZeroDivisionError.

-5 bytes: Use .ord%11%6 instead of a string lookup. Credit goes to user202729

-3 bytes: .ord only considers the first character of the string, so I can skip a [0].

-8 bytes: Use -a flag to automatically split input, thanks to Kirill L.

  • 1
    \$\begingroup\$ You can save even more bytes by adding -a option to do the autosplit for you, like this \$\endgroup\$ – Kirill L. May 2 '18 at 8:55

Emojicode, 270 bytes

🐖🔥🍇🍮c 0🔂j🍡💣🐕🔟 🍇🍊😛j🔤inc🔤🍇🍮c➕c 1🍉🍋😛j🔤dec🔤🍇🍮c➖c 1🍉🍋😛j🔤mult🔤🍇🍮c✖️c 2🍉🍋😛j🔤half🔤🍇🍮c➗c 2🍉🍋😛j🔤Pri🔤🍇👄🔡c 10🍉🍓🍇🍎🍉🍉🍉

Try it online!

🍮c 0
🔂j🍡💣🐕🔟 🍇
🍊😛j🔤inc🔤🍇🍮c➕c 1🍉
🍋😛j🔤dec🔤🍇🍮c➖c 1🍉
🍋😛j🔤mult🔤🍇🍮c✖️c 2🍉
🍋😛j🔤half🔤🍇🍮c➗c 2🍉
🍋😛j🔤Pri🔤🍇👄🔡c 10🍉

 🔥🔤inc inc inc dec Pri exit🔤
 🔥🔤dec inc mult inc inc Pri🔤
 🔥🔤inc inc inc mult half Pri exit inc🔤
 🔥🔤inc Pri inc Pri inc Pri exit half mult🔤
 🔥🔤Pri exit🔤
 🔥🔤inc half Pri exit🔤

SNOBOL4 (CSNOBOL4), 165 bytes

	P =INPUT ' exit ' 
	x =0
S	P LEN(1) $ L ARB ' ' REM . P	:S($L)F(end)
i	X =X + 1	:(S)
d	X =X - 1	:(S)
P	O =O X		:(S)
m	X =X * 2	:(S)
h	X =X / 2.	:(S)

Try it online!


	P =INPUT ' exit ' 				;* append ' exit ' to the input to guarantee that the program will stop
	x =0						;* initialize x to 0 else it won't print properly if the program is 'Pri'
S	P LEN(1) $ L ARB ' ' REM . P	:S($L)F(end)	;* set L to the first letter of the word and goto the appropriate label
i	X =X + 1	:(S)
d	X =X - 1	:(S)
P	O =O X		:(S)				;* append X to the output string
m	X =X * 2	:(S)
h	X =X / 2.	:(S)				;* divide by 2. to ensure floating point
e	OUTPUT =O					;* print whatever's in O, which starts off as ''

C# (.NET Core), 186 Bytes

class P{static void Main(string[]a){int v=0;foreach(var s in a){var i=s[0];if(i=='i')v++;if(i=='d')v--;if(i=='m')v*=2;if(i=='h')v/=2;if(i=='P')System.Console.Write(v);if(i=='e')break;}}}
  • \$\begingroup\$ You can shave 26bytes off this by doing a few simple things, like declaring i with v, consulting an ASCII table so you can use small numbers, rearranging the ifs, and then using a ternary: class Z{static void Main(string[]a){int v=0,i;foreach(var s in a){i=s[0]%'d';if(i==1)break;if(i>9)System.Console.Write(v);else v=i<1?v-1:i<5?v/2:i<6?v+1:v*2;}}} (P.S. an explanation of how it works and how to use it (e.g. expects command line args) is always appreciated!) \$\endgroup\$ – VisualMelon Apr 28 '18 at 7:43
  • \$\begingroup\$ (Oh that is embarrassing... I should have use %50 instead of %'d') \$\endgroup\$ – VisualMelon Apr 28 '18 at 7:51

Perl 5 -a, 61 bytes

eval'$,'.qw(++ -- ;exit ;print$,||0 *=2 /=2)[(ord)%11%6]for@F

Try it online!

Stole @user202729's ord%11%6 trick


-a            # split the input by whitespace, store in @F
eval          # Execute the string that results from:
'$,'          # $, (the accumulator)
.             # appending:
qw(           # create an array for the following whitespace separated values:
++ --            # operators for inc & dec
;exit            # exit
;print$,||0      # Pri  (||0 ensures that 0 is output if accumulator is null
*=2 /=2)         # mult div
[(ord)%11%6] # @user202729's trick selects one of the preceding operations
for@F        # for every term input

Pyth, 44 Bytes


Test Suite


Vmx"idmhPe"hdcwd=Z@[hZtZyZcZ2ZZ)NIqN4pZIqN6B   ## full program
             cwd                               ## split input on space
Vmx"idmhPe"hd                                  ## iterate through list of numbers corresponding to operators
                =Z@[hZtZyZcZ2ZZ)N              ## assign the variable Z (initialliy Zero) it's new value
                                 IqN4pZ        ## print Z if the current operator is "Pri" (4)
                                       IqN6B   ## break if the current operator is "exit" (5)

TI-BASIC, 112 bytes

This takes advantage of some assumptions that are AFAIK perfectly acceptable. Number one being that all variables are initialized to zero prior to execution; number two being that input is taken via Ans.

Ans+" E→Str1
While 1
If inString("MH",Str2
If Str2="P
Disp A
If Str2="E

Java (OpenJDK 8), 164 bytes

a->{int c=0;for(String g:a.split(" ")){char b=g.charAt(0);if(b==105)c++;if(b==100)c--;if(b==109)c*=2;if(b==104)c/=2;if(b==80)System.out.print(c);if(b==101)return;}}

Try it online!

Above is my solution that rounds off to integers, but below is my solution that handles decimals. The obnoxious way that java prints doubles adds another 55 byes to the score. I left the new lines to make the code more readable in the second submission only because it’s essentially the same solution with one extra command and an import statement.

Java (OpenJDK 8), 219 bytes

double c=0;
for(String g:a.split(" ")){
char b=g.charAt(0);
if(b==80)System.out.print(new DecimalFormat("0.#").format(c));

Try it online!


C (gcc), 120 114 111 bytes

-6 bytes thanks to ceilingcat.


Try it online!

124 bytes

Floating-point version:

d;f(char*s){for(float f=0;s>1;s=strchr(s,32)+1)d=*s-80,f+=d==25,f-=d==20,f*=d^29?d^24?1:.5:2,s=d^21?s:"",d?:printf("%f",f);}

Try it online!

I did not bother with a version that rounds down, but makes an exception for 0, which would be allowed, if I understand the comment-chain correctly.


33, 62 bytes


Try it online!

This program takes the instructions delimited by newlines


  [mz            n1a] | Forever
It    jk       It     | - Get the first character of the next instruction
            qz        | - Call the function declared previously
     s  ""lt  t       | - Make sure we don't lose track of the variable

The code before that segment defines all the functions.


Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.