Post Reply 
Walkthrough of an RPL program for an RPN programmer
08-19-2018, 10:15 AM (This post was last modified: 08-19-2018 10:21 AM by Thomas Klemm.)
Post: #4
RE: Walkthrough of an RPL program for an RPN programmer
(08-19-2018 12:17 AM)Albert Chan Wrote:  Perhaps an explanation of how that work ?

Here's a video by Mathologer Burkard Polster:
Gauss's magic shoelace area formula and its calculus companion

Commands
This is a short description of the commands from the user's guide.

DUP
Duplicates object (x).

HEAD
Gets the first element from a list (x).

CROSS
Cross product of two vectors (y ⨯ x).

DOSUBS
Executes a program or command (x) on a specified number of elements at a time (y) within a list (z).

ΣLIST
Adds together all of the elements in a list (x).

ABS
Absolute value of an object (x).

« and »
These mark the begin and end of a code object.


Example
These are the vertices of the cat from the video:

List of Vertices
Code:
{
[ 4 4 ]
[ 0 1 ]
[ -2 5 ]
[ -6 0 ]
[ -1 -4 ]
[ 5 -2 ]
}

They can be entered as a single line:

Enter the List
Code:
{[4 4][0 1][-2 5][-6 0][-1 -4][5 -2]}


Step by Step
Let's go through the program step by step and list the content of the stack.

List of Vertices
Code:
1: {[4 4][0 1][-2 5][-6 0][-1 -4][5 -2]}

DUP
Code:
2: {[4 4][0 1][-2 5][-6 0][-1 -4][5 -2]}
1: {[4 4][0 1][-2 5][-6 0][-1 -4][5 -2]}

HEAD
Code:
2: {[4 4][0 1][-2 5][-6 0][-1 -4][5 -2]}
1: [4 4]

+
Code:
1: {[4 4][0 1][-2 5][-6 0][-1 -4][5 -2][4 4]}

2
Code:
2: {[4 4][0 1][-2 5][-6 0][-1 -4][5 -2][4 4]}
1: 2

« CROSS »
Code:
3: {[4 4][0 1][-2 5][-6 0][-1 -4][5 -2][4 4]}
2: 2
1: « CROSS »

DOSUBS
Code:
1: {[0 0 4][0 0 2][0 0 30][0 0 24][0 0 22][0 0 28]}

ΣLIST
Code:
1: [0 0 110]

ABS
Code:
1: 110

2
Code:
2: 110
1: 2

/
Code:
1: 55

Python

I'm not aware of a way to partition a list in Python. However we can use map with an additional copy of the list that is rotated by one place:

Code:
def cross(A, B):
    return A[0] * B[1] - A[1] * B[0]

def area(P):
    s = map(cross, P, P[1:]+P[0:1])
    return abs(sum(s)) / 2

Example:
Code:
>>> cat = [(4,4), (0,1), (-2,5), (-6,0), (-1,-4), (5,-2)]
>>> area(cat)
55.0

Clojure

Code:
(defn cross [[[a b] [c d]]]
    (- (* a d) (* b c)))

(defn area [polygon]
    (/ (reduce + (map cross (partition 2 1 [(first polygon)] polygon))) 2))

We can make that area function a bit more readable using threading macros -> and ->>:
Code:
(defn area [polygon]
    (->
    (->> polygon
    (partition 2 1 [(first polygon)])
    (map cross)
    (reduce +))
    (/ 2)))

Example:
Code:
user=> (def polygon [[4 4][0 1][-2 5][-6 0][-1 -4][5 -2]])
#'user/polygon
user=> (area polygon)
55

SQL

I haven't tried but DOSUB and partition remind me of window functions in SQL.

Kind regards
Thomas
Find all posts by this user
Quote this message in a reply
Post Reply 


Messages In This Thread
RE: Walkthrough of an RPL program for an RPN programmer - Thomas Klemm - 08-19-2018 10:15 AM



User(s) browsing this thread: 3 Guest(s)