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.)

   clear =: 3 : ',.STACK =: '''''
   enter =: 4 : ',.STACK =: STACK , x'  NB. x a list of numbers
   chs =: 3 : ',.STACK =: (_1 }. STACK), - _1 {. STACK'
   dup =: 4 : ',.STACK =: STACK , (- x) {. STACK'  NB. x a non-negative
integer
   plus =: 3 : ',.STACK =: ( _2 }. STACK), +/ _2 {. STACK'
   minus =: 3 : ',.STACK =: ( _2 }. STACK), -/ _2 {. STACK'
   times =: 3 : ',.STACK =: ( _2 }. STACK), */ _2 {. STACK'
   divide =: 3 : ',.STACK =: ( _2 }. STACK), %/ _2 {. STACK'

   clear''
   1 2 enter ''
1
2
   chs ''   NB. Change sign of bottom number
 1
_2
   2 dup''  NB. Can use dup to keep a copy of numbers about to be combined
 1
_2
 1
_2
   plus''  NB. 1 plus _2 is _1
 1
_2
_1





-- 
Sent from Gmail Mobile
----------------------------------------------------------------------
For information about J forums see http://www.jsoftware.com/forums.htm

Reply via email to