5 KiB
Seven More Languages in Seven Weeks
Introduction
Introduction
Factor BMCOL
FACTOR
A stack-based, concatenative programming language
Mr. Miyagi BMCOL
Day 1
Day 1: Stack On, Stack Off
- Installing Factor
- Using the REPL
- Basic Syntax & Data Types
- Stack Shuffling
- Combinators
Getting Stacked
"Hello, world" print
! Hello, world
"same" length "diff" length = .
! t
Data Types
- Booleans
-
t
orf
- Sequences
-
- Lists
{ 4 3 2 1 }
- Maps
{ { "one" 1 } { "two" 2 } { "three" 3 } }
- Quotations
-
[ 42 + ]
Conditionals
Conditionals take quotations as branching arguments
10 0 > [ "pos" ] [ "neg" ] if .
! pos
-5 0 > [ "pos" ] [ "neg" ] if .
! neg
Stack Shuffling
- dup
- Duplicate a value on the stack
- drop
- Drop the top value from the stack
- nip
- Drop the second value
- swap
- Swap two values
- over
- Duplicates the second value over to the top
- rot
- Rotate the top 3 values on the stack
Combinators
bi
,bi@
,bi*
tri
,tri@
,tri*
dip
,keep
44.50 [ 0.05 * ] [ 0.09975 * ] bi
! 2.225
! 4.438875
44.50 22.50 [ 0.05 * ] bi@
! 2.225
! 1.125
44.50 22.50 [ 0.05 * ] [ 0.09975 * ] bi*
! 2.225
! 2.244375
Exercises
Exercises
Easy B_note
Using only * and + , how would you calculate 3^2 + 4^2 with Factor?
4 dup * 3 dup * + .
Enter USE: math.functions in the Listener. Now, with sq and sqrt , calculate the square root of 3^2 + 4^2 .
3 sq 4 sq + sqrt .
1 2
over swap
USE: ascii
"Correl" "Hello, " swap append >upper .
Medium B_note
Day 2
Day 2: Painting the Fence
- Defining Words
- Vocabularies
- Unit Tests
- Interview with Slava Pestov
Defining Words
: add-42 ( x -- y ) 42 + ;
: sum ( seq -- n ) 0 [ + ] reduce ;
: first-two ( seq -- a b ) [ first ] [ second ] bi ;
Vocabularies
Words are organized into vocabularies, which are similar to packages, modules, or namespaces in other languages.
Unit Tests
Factor includes a unit testing vocabulary (tools.test
), which is
useful for ensuring correctness of your code, and also experimenting
with the language.
USING: examples.greeter tools.test ;
IN: examples.greeter.tests
{ "Hello, Test" } [ "Test" greeting ] unit-test
Interview with Slava Pestov
I decided to write my own language, though, because I wanted something really simple, and also just because it would be fun.
Exercises
Exercises
Day 3
Day 3: Balancing on the Boat
- Tuples
- Pipelining with Higher-Order Words
Tuples
-
Defining
TUPLE: name slot ... ;
-
Accessing and Modifying
slot>>
>>slot
change-slot
-
Creating
boa
(By Order of Arguments)T{ name { slot value } ... }
Higher-Order Words
CONSTANT: gst-rate 0.05
CONSTANT: pst-rate 0.09975
: gst-pst ( price -- taxes ) [ gst-rate * ] [ pst-rate * ] bi + ;
: taxes ( checkout taxes-calc -- taxes )
[ dup base-price>> ] dip
call >>taxes ; inline
The inline
keyword is necessary, as the taxes
word takes
quotations as parameters.
Wrapping Up
Wrapping Up
Strengths
- Simple syntax
- Easy function composition
- Batteries included
Weaknesses
- Learning curve
- Small community
- Limited resources
Final Thoughts
Final Thoughts