What would I do? I'd use this opportunity to practice adverbial programming. (Yes, thank you, I've learned from your answers to my tacit adverb questions.) I've changed your definition of clear so that y sets the initial stack, and of dup. All of the j stack manipulation verbs are monadic. Excepting clear, enter, and dupkip, they ignore y. To do: handle errors, write an interpreter, other.

Stack =: 1 : ' ,.STACK =: ((STACK"_) :: (''''"_) 0) u y'

NB. u Monad replaces top of stack with  u TOS
Monad =: (@:{:)(]`}:`,`)(`:6)~ Stack

NB. u Dyad replaces top 2 items with the
NB. result of inserting u between them.
Dyad =: (/)(]`(_2&}.)`,`[:`)(`(_2&{.))(`:6)~ Stack

clear =: ] Stack
enter =: , Stack
dupkip =: ([ , ({.~ -)) Stack

rot3 =: ((_3 }. [) , _1 |. _3 {. [) Stack

dup =: 2&# Monad
reciprocal =: % Monad
chs =: - Monad

plus =: + Dyad
minus =: - Dyad
times =: * Dyad
divide =: % Dyad
exch =: ,~ Dyad

   clear'eta'
e
t
a
   exch''
e
a
t
   rot3''
t
e
a
   enter'm'
t
e
a
m


   clear i.8
0
1
2
3
4
5
6
7
   reciprocal''
       0
       1
       2
       3
       4
       5
       6
0.142857
   divide''
 0
 1
 2
 3
 4
 5
42
   square =: times@dup   NB. or  *: Monad
   square''
   0
   1
   2
   3
   4
   5
1764

Date: Thu, 5 Jun 2014 00:45:40 -0500
From: Kip Murray<[email protected]>
To:"[email protected]"  <[email protected]>
Subject: [Jprogramming] rpn calculator
Message-ID:
        <CAOfWorgKZnCkZtgFd6L6=_6nmquuhbyot0usypwatygf6b+...@mail.gmail.com>
Content-Type: text/plain; charset=UTF-8

The following emulates a simple reverse Polish notation calculator which
operates on numbers at the bottom of a stack, replacing them by the result.
  How would you do it?  (Beware of line wrap.)

----------------------------------------------------------------------
For information about J forums see http://www.jsoftware.com/forums.htm

Reply via email to