Merged racket changes

This commit is contained in:
Adam 2013-07-17 10:06:29 -07:00
commit b1fe88fe17
2 changed files with 350 additions and 193 deletions

View File

@ -6,7 +6,7 @@ filename: learnerlang.erl
--- ---
```erlang ```erlang
% Percent sign start a one-line comment. % Percent sign starts an one-line comment.
%% Two percent characters shall be used to comment functions. %% Two percent characters shall be used to comment functions.
@ -17,7 +17,7 @@ filename: learnerlang.erl
% patterns. % patterns.
% Periods (`.`) (followed by whitespace) separate entire functions and % Periods (`.`) (followed by whitespace) separate entire functions and
% expressions in the shell. % expressions in the shell.
% Semicolons (`;`) separate clauses. We find clauses in several contexts: in kn % Semicolons (`;`) separate clauses. We find clauses in several contexts:
% function definitions and in `case`, `if`, `try..catch` and `receive` % function definitions and in `case`, `if`, `try..catch` and `receive`
% expressions. % expressions.
@ -26,8 +26,10 @@ filename: learnerlang.erl
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
Num = 42. % All variable names must start with an uppercase letter. Num = 42. % All variable names must start with an uppercase letter.
% Erlang has single assignment variables, if you try to assign a different value % Erlang has single assignment variables, if you try to assign a different value
% to the variable `Num`, youll get an error. % to the variable `Num`, youll get an error.
Num = 43. % ** exception error: no match of right hand side value 43
% In most languages, `=` denotes an assignment statement. In Erlang, however, % In most languages, `=` denotes an assignment statement. In Erlang, however,
% `=` denotes a pattern matching operation. `Lhs = Rhs` really means this: % `=` denotes a pattern matching operation. `Lhs = Rhs` really means this:
@ -42,6 +44,11 @@ Pi = 3.14159.
% start with lowercase letters, followed by a sequence of alphanumeric % start with lowercase letters, followed by a sequence of alphanumeric
% characters or the underscore (`_`) or at (`@`) sign. % characters or the underscore (`_`) or at (`@`) sign.
Hello = hello. Hello = hello.
OtherNode = example@node.
% Atoms with non alphanumeric values can be written by enclosing the atoms
% with apostrophes.
AtomWithSpace = 'some atom with space'.
% Tuples are similar to structs in C. % Tuples are similar to structs in C.
Point = {point, 10, 45}. Point = {point, 10, 45}.
@ -60,15 +67,15 @@ Person = {person, {name, {first, joe}, {last, armstrong}}, {footsize, 42}}.
% We create a list by enclosing the list elements in square brackets and % We create a list by enclosing the list elements in square brackets and
% separating them with commas. % separating them with commas.
% The individual elements of a list can be of any type. % The individual elements of a list can be of any type.
% The first element of a list the head of the list. If you imagine removing the % The first element of a list is the head of the list. If you imagine removing the
% head from the list, whats left is called the tail of the list. % head from the list, whats left is called the tail of the list.
ThingsToBuy = [{apples, 10}, {pears, 6}, {milk, 3}]. ThingsToBuy = [{apples, 10}, {pears, 6}, {milk, 3}].
% If `T` is a list, then `[H|T]` is also a list, with head H and tail T. % If `T` is a list, then `[H|T]` is also a list, with head `H` and tail `T`.
% The vertical bar (`|`) separates the head of a list from its tail. % The vertical bar (`|`) separates the head of a list from its tail.
% `[]` is the empty list. % `[]` is the empty list.
% We can extract elements from a list with a pattern matching operation. If we % We can extract elements from a list with a pattern matching operation. If we
% have the nonempty list `L`, then the expression `[X|Y] = L`, where `X` and `Y` % have a nonempty list `L`, then the expression `[X|Y] = L`, where `X` and `Y`
% are unbound variables, will extract the head of the list into `X` and the tail % are unbound variables, will extract the head of the list into `X` and the tail
% of the list into `Y`. % of the list into `Y`.
[FirstThing|OtherThingsToBuy] = ThingsToBuy. [FirstThing|OtherThingsToBuy] = ThingsToBuy.
@ -78,6 +85,7 @@ ThingsToBuy = [{apples, 10}, {pears, 6}, {milk, 3}].
% There are no strings in Erlang. Strings are really just lists of integers. % There are no strings in Erlang. Strings are really just lists of integers.
% Strings are enclosed in double quotation marks (`"`). % Strings are enclosed in double quotation marks (`"`).
Name = "Hello". Name = "Hello".
[72, 101, 108, 108, 111] = "Hello".
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
@ -89,9 +97,9 @@ Name = "Hello".
% Modules must be compiled before the code can be run. A compiled module has the % Modules must be compiled before the code can be run. A compiled module has the
% extension `.beam`. % extension `.beam`.
-module(geometry). -module(geometry).
-export([area/1]). -export([area/1]). % the list of functions exported from the module.
% The function area consists of two clauses. The clauses are separated by a % The function `area` consists of two clauses. The clauses are separated by a
% semicolon, and the final clause is terminated by dot-whitespace. % semicolon, and the final clause is terminated by dot-whitespace.
% Each clause has a head and a body; the head consists of a function name % Each clause has a head and a body; the head consists of a function name
% followed by a pattern (in parentheses), and the body consists of a sequence of % followed by a pattern (in parentheses), and the body consists of a sequence of
@ -109,17 +117,17 @@ c(geometry). % {ok,geometry}
geometry:area({rectangle, 10, 5}). % 50 geometry:area({rectangle, 10, 5}). % 50
geometry:area({circle, 1.4}). % 6.15752 geometry:area({circle, 1.4}). % 6.15752
% In Erlang, two functions with the same name and different arity in the same % In Erlang, two functions with the same name and different arity (number of arguments)
% module represent entirely different functions. % in the same module represent entirely different functions.
-module(lib_misc). -module(lib_misc).
-export([sum/1]). -export([sum/1]). % export function `sum` of arity 1 accepting one argument: list of integers.
sum(L) -> sum(L, 0). sum(L) -> sum(L, 0).
sum([], N) -> N; sum([], N) -> N;
sum([H|T], N) -> sum(T, H+N). sum([H|T], N) -> sum(T, H+N).
% Funs are "anonymous" functions. They are called this because they have no % Funs are "anonymous" functions. They are called this way because they have no
% name. % name. However they can be assigned to variables.
Double = fun(X) -> 2*X end. Double = fun(X) -> 2*X end. % `Double` points to an anonymous function with handle: #Fun<erl_eval.6.17052888>
Double(2). % 4 Double(2). % 4
% Functions accept funs as their arguments and can return funs. % Functions accept funs as their arguments and can return funs.
@ -133,6 +141,8 @@ Triple(5). % 15
% from the list `L`." % from the list `L`."
L = [1,2,3,4,5]. L = [1,2,3,4,5].
[2*X || X <- L]. % [2,4,6,8,10] [2*X || X <- L]. % [2,4,6,8,10]
% A list comprehension can have generators and filters which select subset of the generated values.
EvenNumbers = [N || N <- [1, 2, 3, 4], N rem 2 == 0]. % [2, 4]
% Guards are constructs that we can use to increase the power of pattern % Guards are constructs that we can use to increase the power of pattern
% matching. Using guards, we can perform simple tests and comparisons on the % matching. Using guards, we can perform simple tests and comparisons on the
@ -181,7 +191,7 @@ X2 = X1#todo{status = done}.
% #todo{status = done,who = joe,text = "Fix errata in book"} % #todo{status = done,who = joe,text = "Fix errata in book"}
% `case` expressions. % `case` expressions.
% `filter` returns a list of all those elements `X` in `L` for which `P(X)` is % `filter` returns a list of all elements `X` in a list `L` for which `P(X)` is
% true. % true.
filter(P, [H|T]) -> filter(P, [H|T]) ->
case P(H) of case P(H) of
@ -189,6 +199,7 @@ filter(P, [H|T]) ->
false -> filter(P, T) false -> filter(P, T)
end; end;
filter(P, []) -> []. filter(P, []) -> [].
filter(fun(X) -> X rem 2 == 0 end, [1, 2, 3, 4]). % [2, 4]
% `if` expressions. % `if` expressions.
max(X, Y) -> max(X, Y) ->
@ -198,7 +209,7 @@ max(X, Y) ->
true -> nil; true -> nil;
end. end.
% Warning: at least one of the guards in the if expression must evaluate to true; % Warning: at least one of the guards in the `if` expression must evaluate to true;
% otherwise, an exception will be raised. % otherwise, an exception will be raised.
@ -234,6 +245,7 @@ catcher(N) -> catch generate_exception(N).
## References ## References
* "Programming Erlang: Software for a Concurrent World" by Joe Armstrong * ["Learn You Some Erlang for great good!"](http://learnyousomeerlang.com/)
* ["Programming Erlang: Software for a Concurrent World" by Joe Armstrong](http://pragprog.com/book/jaerlang/programming-erlang)
* [Erlang/OTP Reference Documentation](http://www.erlang.org/doc/)
* [Erlang - Programming Rules and Conventions](http://www.erlang.se/doc/programming_rules.shtml) * [Erlang - Programming Rules and Conventions](http://www.erlang.se/doc/programming_rules.shtml)
* [Erlang/OTP Documentation](http://www.erlang.org/doc/)

View File

@ -1,8 +1,10 @@
--- ---
language: racket language: racket
filename: learnracket.rkt
contributors: contributors:
- ["th3rac25", "http://twitter.com/th3rac25"] - ["th3rac25", "https://github.com/voila"]
filename: learnracket.py - ["Eli Barzilay", "https://github.com/elibarzilay"]
--- ---
Racket is a general purpose, multi-paradigm programming language in the Lisp/Scheme family. Racket is a general purpose, multi-paradigm programming language in the Lisp/Scheme family.
@ -15,17 +17,18 @@ Feedback is appreciated! You can reach me at [@th3rac25](http://twitter.com/th3r
;;; Comments ;;; Comments
; Single line comments start with a semicolon ;; Single line comments start with a semicolon
#| Block comments #| Block comments
can span multiple lines and... can span multiple lines and...
#| #|
they can be nested ! they can be nested!
|# |#
|# |#
; S-expression comments discard the following expression ;; S-expression comments discard the following expression,
#; "this expression will be discarded" "2nd expression" ; => "2nd expression" ;; useful to comment expressions when debugging
#; (this expression is discarded)
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; 1. Primitive Datatypes and Operators ;; 1. Primitive Datatypes and Operators
@ -33,20 +36,24 @@ Feedback is appreciated! You can reach me at [@th3rac25](http://twitter.com/th3r
;;; Numbers ;;; Numbers
9999999999999999999999 ; integers 9999999999999999999999 ; integers
#b111 ; binary => 7
#o111 ; octal => 73
#x111 ; hexadecimal => 273
3.14 ; reals 3.14 ; reals
6.02e+23 6.02e+23
1/2 ; rationals 1/2 ; rationals
1+2i ; complex numbers 1+2i ; complex numbers
; Function application is written (f x y z ...) ;; Function application is written (f x y z ...)
; where f is a function and x, y, z, ... are operands ;; where f is a function and x, y, z, ... are operands
; If you want to create a literal list of data, use ' to stop it from ;; If you want to create a literal list of data, use ' to stop it from
; being evaluated ;; being evaluated
'(+ 1 2) ; => (+ 1 2) '(+ 1 2) ; => (+ 1 2)
; Now, some arithmetic operations ;; Now, some arithmetic operations
(+ 1 1) ; => 2 (+ 1 1) ; => 2
(- 8 1) ; => 7 (- 8 1) ; => 7
(* 10 2) ; => 20 (* 10 2) ; => 20
(expt 2 3) ; => 8
(quotient 5 2) ; => 2 (quotient 5 2) ; => 2
(remainder 5 2) ; => 1 (remainder 5 2) ; => 1
(/ 35 5) ; => 7 (/ 35 5) ; => 7
@ -68,46 +75,47 @@ Feedback is appreciated! You can reach me at [@th3rac25](http://twitter.com/th3r
;;; Strings are fixed-length array of characters. ;;; Strings are fixed-length array of characters.
"Hello, world!" "Hello, world!"
"Benjamin \"Bugsy\" Siegel" ; backslash is an escaping character "Benjamin \"Bugsy\" Siegel" ; backslash is an escaping character
"λx:(μα.α→α).xx" ; any Unicode character can appear in a string constant "Foo\tbar\41\x21\u0021\a\r\n" ; includes C escapes, Unicode
"λx:(μα.α→α).xx" ; can include Unicode characters
; Strings can be added too! ;; Strings can be added too!
(string-append "Hello " "world!") ; => "Hello world!" (string-append "Hello " "world!") ; => "Hello world!"
; A string can be treated like a list of characters ;; A string can be treated like a list of characters
(string-ref "Apple" 0) ; => #\A (string-ref "Apple" 0) ; => #\A
; format can be used to format strings: ;; format can be used to format strings:
(format "~a can be ~a" "strings" "formatted") (format "~a can be ~a" "strings" "formatted")
; Printing is pretty easy ;; Printing is pretty easy
(printf "I'm Racket. Nice to meet you!\n") (printf "I'm Racket. Nice to meet you!\n")
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; 2. Variables ;; 2. Variables
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
; You can create a variable using define ;; You can create a variable using define
; a variable name can use any character except: ()[]{}",'`;#|\ ;; a variable name can use any character except: ()[]{}",'`;#|\
(define some-var 5) (define some-var 5)
some-var ; => 5 some-var ; => 5
; You can also use unicode characters ;; You can also use unicode characters
(define ⊆ subset?) (define ⊆ subset?)
(⊆ (set 3 2) (set 1 2 3)); => #t (⊆ (set 3 2) (set 1 2 3)) ; => #t
; Accessing a previously unassigned variable is an exception ;; Accessing a previously unassigned variable is an exception
;x ; => x: undefined ... ; x ; => x: undefined ...
; Local binding: me is bound to "Bob" only within (let ...) ;; Local binding: `me' is bound to "Bob" only within the (let ...)
(let ([me "Bob"]) (let ([me "Bob"])
"Alice" "Alice"
me) ; => "Bob" me) ; => "Bob"
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; 3. Structs and Collections ;; 3. Structs and Collections
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
; Structs ;; Structs
(struct dog (name breed age)) (struct dog (name breed age))
(define my-pet (define my-pet
(dog "lassie" "collie" 5)) (dog "lassie" "collie" 5))
@ -116,127 +124,170 @@ my-pet ; => #<dog>
(dog-name my-pet) ; => "lassie" (dog-name my-pet) ; => "lassie"
;;; Pairs (immutable) ;;; Pairs (immutable)
; "cons" constructs pairs, "car" and "cdr" extract the first ;; `cons' constructs pairs, `car' and `cdr' extract the first
; and second elements ;; and second elements
(cons 1 2) ; => '(1 . 2) (cons 1 2) ; => '(1 . 2)
(car (cons 1 2)) ; => 1 (car (cons 1 2)) ; => 1
(cdr (cons 1 2)) ; => 2 (cdr (cons 1 2)) ; => 2
;;; Lists ;;; Lists
; Lists are linked-list data structures ;; Lists are linked-list data structures, made of `cons' pairs and end
;; with a `null' (or '()) to mark the end of the list
(cons 1 (cons 2 (cons 3 null))) ; => '(1 2 3)
;; `list' is a convenience variadic constructor for lists
(list 1 2 3) ; => '(1 2 3) (list 1 2 3) ; => '(1 2 3)
;; and a quote can also be used for a literal list value
'(1 2 3) ; => '(1 2 3)
; Use "cons" to add an item to the beginning of a list ;; Can still use `cons' to add an item to the beginning of a list
(cons 4 '(1 2 3)) ; => (4 1 2 3) (cons 4 '(1 2 3)) ; => '(4 1 2 3)
; Use "append" to add lists together ;; Use `append' to add lists together
(append '(1 2) '(3 4)) ; => (1 2 3 4) (append '(1 2) '(3 4)) ; => '(1 2 3 4)
;; Lists are a very basic type, so there is a *lot* of functionality for
;; them, a few examples:
(map add1 '(1 2 3)) ; => '(2 3 4)
(map + '(1 2 3) '(10 20 30)) ; => '(11 22 33)
(filter even? '(1 2 3 4)) ; => '(2 4)
(count even? '(1 2 3 4)) ; => 2
(take '(1 2 3 4) 2) ; => '(1 2)
(drop '(1 2 3 4) 2) ; => '(3 4)
;;; Vectors ;;; Vectors
; Vectors are fixed-length arrays ;; Vectors are fixed-length arrays
#(1 2 3) ; => '#(1 2 3) #(1 2 3) ; => '#(1 2 3)
; Use "vector-append" to add vectors together ;; Use `vector-append' to add vectors together
(vector-append #(1 2 3) #(4 5 6)) ; => #(1 2 3 4 5 6) (vector-append #(1 2 3) #(4 5 6)) ; => #(1 2 3 4 5 6)
;;; Sets ;;; Sets
; create a set from a list ;; Create a set from a list
(list->set '(1 2 3 1 2 3 3 2 1 3 2 1)) ; => (set 1 2 3) (list->set '(1 2 3 1 2 3 3 2 1 3 2 1)) ; => (set 1 2 3)
; Add a member with "set-add" ;; Add a member with `set-add'
(set-add (set 1 2 3) 4); => (set 1 2 3 4) ;; (Functional: returns the extended set rather than mutate the input)
(set-add (set 1 2 3) 4) ; => (set 1 2 3 4)
; Remove one with "set-remove" ;; Remove one with `set-remove'
(set-remove (set 1 2 3) 1) ; => (set 2 3) (set-remove (set 1 2 3) 1) ; => (set 2 3)
; Test for existence with "set-member?" ;; Test for existence with `set-member?'
(set-member? (set 1 2 3) 1) ; => #t (set-member? (set 1 2 3) 1) ; => #t
(set-member? (set 1 2 3) 4) ; => #f (set-member? (set 1 2 3) 4) ; => #f
;;; Hashes ;;; Hashes
; Create an immutable hash table (There are also mutables ones) ;; Create an immutable hash table (mutable example below)
(define m (hash 'a 1 'b 2 'c 3)) (define m (hash 'a 1 'b 2 'c 3))
; Retrieve a value ;; Retrieve a value
(hash-ref m 'a) ; => 1 (hash-ref m 'a) ; => 1
; Retrieving a non-present value is an exception ;; Retrieving a non-present value is an exception
; (hash-ref m 'd) => no value found ; (hash-ref m 'd) => no value found
; You can provide a default value for missing keys ;; You can provide a default value for missing keys
(hash-ref m 'd 0) ; => 0 (hash-ref m 'd 0) ; => 0
; Use "hash-set" to extend a hash table ;; Use `hash-set' to extend an immutable hash table
;; (Returns the extended hash instdead of mutating it)
(define m2 (hash-set m 'd 4)) (define m2 (hash-set m 'd 4))
m2 ; => '#hash((b . 2) (a . 1) (d . 4) (c . 3)) m2 ; => '#hash((b . 2) (a . 1) (d . 4) (c . 3))
; Remember, these hashes are immutable! ;; Remember, these hashes are immutable!
m ; => '#hash((b . 2) (a . 1) (c . 3)) m ; => '#hash((b . 2) (a . 1) (c . 3)) <-- no `d'
; Use "hash-remove" to remove keys ;; Use `hash-remove' to remove keys (functional too)
(hash-remove m 'a) ; => '#hash((b . 2) (c . 3)) (hash-remove m 'a) ; => '#hash((b . 2) (c . 3))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; 3. Functions ;; 3. Functions
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
; Use lambda to create new functions. ;; Use `lambda' to create functions.
; A function always returns its last statement. ;; A function always returns the value of its last expression
(lambda () "Hello World") ; => #<procedure> (lambda () "Hello World") ; => #<procedure>
;; Can also use a unicode `λ'
(λ () "Hello World") ; => same function
; (You need extra parens to call it) ;; Use parens to call all functions, including a lambda expression
((lambda () "Hello World")) ; => "Hello World" ((lambda () "Hello World")) ; => "Hello World"
((λ () "Hello World")) ; => "Hello World"
; Assign a function to a var ;; Assign a function to a var
(define hello-world (lambda () "Hello World")) (define hello-world (lambda () "Hello World"))
(hello-world) ; => "Hello World" (hello-world) ; => "Hello World"
; You can shorten this to: ;; You can shorten this using the function definition syntatcic sugae:
(define (hello-world2) "Hello World") (define (hello-world2) "Hello World")
; The () is the list of arguments for the function. ;; The () in the above is the list of arguments for the function
(define hello (define hello
(lambda (name) (lambda (name)
(string-append "Hello " name))) (string-append "Hello " name)))
(hello "Steve") ; => "Hello Steve" (hello "Steve") ; => "Hello Steve"
;; ... or equivalently, using a sugared definition:
(define (hello2 name)
(string-append "Hello " name))
; You can have multi-variadic functions, too ;; You can have multi-variadic functions too, using `case-lambda'
(define hello2 (define hello3
(case-lambda (case-lambda
[() "Hello World"] [() "Hello World"]
[(name) (string-append "Hello " name)])) [(name) (string-append "Hello " name)]))
(hello2 "Jake") ; => "Hello Jake" (hello3 "Jake") ; => "Hello Jake"
(hello2) ; => "Hello World" (hello3) ; => "Hello World"
;; ... or specify optional arguments with a default value expression
(define (hello4 [name "World"])
(string-append "Hello " name))
; Functions can pack extra arguments up in a list ;; Functions can pack extra arguments up in a list
(define (count-args . args) (define (count-args . args)
(format "You passed ~a args: ~a" (length args) args)) (format "You passed ~a args: ~a" (length args) args))
(count-args 1 2 3) ; => "You passed 3 args: (1 2 3)" (count-args 1 2 3) ; => "You passed 3 args: (1 2 3)"
;; ... or with the unsugared `lambda' form:
(define count-args2
(lambda args
(format "You passed ~a args: ~a" (length args) args)))
; You can mix regular and packed arguments ;; You can mix regular and packed arguments
(define (hello-count name . args) (define (hello-count name . args)
(format "Hello ~a, you passed ~a extra args" name (length args))) (format "Hello ~a, you passed ~a extra args" name (length args)))
(hello-count "Finn" 1 2 3) (hello-count "Finn" 1 2 3)
; => "Hello Finn, you passed 3 extra args" ; => "Hello Finn, you passed 3 extra args"
;; ... unsugared:
(define hello-count2
(lambda (name . args)
(format "Hello ~a, you passed ~a extra args" name (length args))))
;; And with keywords
(define (hello-k #:name [name "World"] #:greeting [g "Hello"] . args)
(format "~a ~a, ~a extra args" g name (length args)))
(hello-k) ; => "Hello World, 0 extra args"
(hello-k 1 2 3) ; => "Hello World, 3 extra args"
(hello-k #:greeting "Hi") ; => "Hi World, 0 extra args"
(hello-k #:name "Finn" #:greeting "Hey") ; => "Hey Finn, 0 extra args"
(hello-k 1 2 3 #:greeting "Hi" #:name "Finn" 4 5 6)
; => "Hi Finn, 6 extra args"
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; 4. Equality ;; 4. Equality
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
; for numbers use "=" ;; for numbers use `='
(= 3 3.0) ; => #t (= 3 3.0) ; => #t
(= 2 1) ; => #f (= 2 1) ; => #f
; for object identity use "eq?" ;; for object identity use `eq?'
(eq? 3 3) ; => #t (eq? 3 3) ; => #t
(eq? 3 3.0) ; => #f (eq? 3 3.0) ; => #f
(eq? (list 3) (list 3)) ; => #f (eq? (list 3) (list 3)) ; => #f
; for collections use "equal?" ;; for collections use `equal?'
(equal? (list 'a 'b) (list 'a 'b)) ; => #t (equal? (list 'a 'b) (list 'a 'b)) ; => #t
(equal? (list 'a 'b) (list 'b 'a)) ; => #f (equal? (list 'a 'b) (list 'b 'a)) ; => #f
@ -248,20 +299,20 @@ m ; => '#hash((b . 2) (a . 1) (c . 3))
(if #t ; test expression (if #t ; test expression
"this is true" ; then expression "this is true" ; then expression
"this is false" ; else expression "this is false") ; else expression
) ; => "this is true" ; => "this is true"
; In conditionals, all non-#f values are treated as true ;; In conditionals, all non-#f values are treated as true
(member "Groucho" '("Harpo" "Groucho" "Zeppo")) ; => '("Groucho" "Zeppo") (member 'Groucho '(Harpo Groucho Zeppo)) ; => '(Groucho Zeppo)
(if (member "Groucho" '("Harpo" "Groucho" "Zeppo")) (if (member 'Groucho '(Harpo Groucho Zeppo))
'yep 'yep
'nope) ; => 'yep 'nope)
; => 'yep
; "cond" chains a series of tests to select a result ;; `cond' chains a series of tests to select a result
(cond (cond [(> 2 2) (error "wrong!")]
[(> 2 2) (error "wrong!")] [(< 2 2) (error "wrong again!")]
[(< 2 2) (error "wrong again!")] [else 'ok]) ; => 'ok
[else 'ok]) ; => 'ok
;;; Pattern Matching ;;; Pattern Matching
@ -277,39 +328,30 @@ m ; => '#hash((b . 2) (a . 1) (c . 3))
;;; Loops ;;; Loops
; looping can be done through recursion ;; Looping can be done through (tail-) recursion
(define (loop i) (define (loop i)
(when (< i 10) (when (< i 10)
(printf "i:~a~n" i) (printf "i=~a\n" i)
(loop (add1 i)))) (loop (add1 i))))
(loop 5) ; => i=5, i=6, ...
(loop 5) ; => i:5 i:6 ... ;; Similarly, with a named let
; similarly, with a named let
(let loop ((i 0)) (let loop ((i 0))
(when (< i 10) (when (< i 10)
(printf "i:~a~n" i) (printf "i=~a\n" i)
(loop (add1 i)))) ; => i:0 i:1 ... (loop (add1 i)))) ; => i=0, i=1, ...
;;; Comprehensions ;; See below how to add a new `loop' form, but Racket already has a very
;; flexible `for' form for loops:
(for ([i 10])
(printf "i=~a\n" i)) ; => i=0, i=1, ...
(for ([i (in-range 5 10)])
(printf "i=~a\n" i)) ; => i=5, i=6, ...
(for/list ([i '(1 2 3)]) ;;; Iteration Over Other Sequences
(add1 i)) ; => '(2 3 4) ;; `for' allows iteration over many other kinds of sequences:
;; lists, vectors, strings, sets, hash tables, etc...
(for/list ([i '(1 2 3)] #:when (even? i))
i) ; => '(2)
(for/hash ([i '(1 2 3)])
(values i (number->string i))) ; => '#hash((1 . "1") (2 . "2") (3 . "3"))
; To combine iteration results, use "for/fold"
(for/fold ([sum 0]) ([i '(1 2 3 4)])
(+ sum i)) ; => 10
;;; Sequences
; "for" allows iteration over sequences:
; lists, vectors, strings, sets, hash tables, etc...
(for ([i (in-list '(l i s t))]) (for ([i (in-list '(l i s t))])
(displayln i)) (displayln i))
@ -323,42 +365,113 @@ m ; => '#hash((b . 2) (a . 1) (c . 3))
(displayln i)) (displayln i))
(for ([(k v) (in-hash (hash 'a 1 'b 2 'c 3 ))]) (for ([(k v) (in-hash (hash 'a 1 'b 2 'c 3 ))])
(printf "key:~a value:~a ~n" k v)) (printf "key:~a value:~a\n" k v))
;;; More Complex Iterations
;; Parallel scan of multiple sequences (stops on shortest)
(for ([i 10] [j '(x y z)]) (printf "~a:~a\n" i j))
; => 0:x 1:y 2:z
;; Nested loops
(for* ([i 2] [j '(x y z)]) (printf "~a:~a\n" i j))
; => 0:x, 0:y, 0:z, 1:x, 1:y, 1:z
;; Conditions
(for ([i 1000]
#:when (> i 5)
#:unless (odd? i)
#:break (> i 10))
(printf "i=~a\n" i))
; => i=6, i=8, i=10
;;; Comprehensions
;; Very similar to `for' loops -- just collect the results
(for/list ([i '(1 2 3)])
(add1 i)) ; => '(2 3 4)
(for/list ([i '(1 2 3)] #:when (even? i))
i) ; => '(2)
(for/list ([i 10] [j '(x y z)])
(list i j)) ; => '((0 x) (1 y) (2 z))
(for/list ([i 1000] #:when (> i 5) #:unless (odd? i) #:break (> i 10))
i) ; => '(6 8 10)
(for/hash ([i '(1 2 3)])
(values i (number->string i)))
; => '#hash((1 . "1") (2 . "2") (3 . "3"))
;; There are many kinds of other built-in ways to collect loop values:
(for/sum ([i 10]) (* i i)) ; => 285
(for/product ([i (in-range 1 11)]) (* i i)) ; => 13168189440000
(for/and ([i 10] [j (in-range 10 20)]) (< i j)) ; => #t
(for/or ([i 10] [j (in-range 0 20 2)]) (= i j)) ; => #t
;; And to use any arbitrary combination, use `for/fold'
(for/fold ([sum 0]) ([i '(1 2 3 4)]) (+ sum i)) ; => 10
;; (This can often replace common imperative loops)
;;; Exceptions ;;; Exceptions
; To catch an exception, use the "with-handlers" form ;; To catch exceptions, use the `with-handlers' form
; To throw an exception use "raise" (with-handlers ([exn:fail? (lambda (exn) 999)])
(with-handlers (+ 1 "2")) ; => 999
([(lambda (v) (equal? v "infinity")) (with-handlers ([exn:break? (lambda (exn) "no time")])
(lambda (exn) +inf.0)]) (sleep 3)
(raise "infinity")) "phew") ; => "phew", but if you break it => "no time"
;; Use `raise' to throw exceptions or any other value
(with-handlers ([number? ; catch numeric values raised
identity]) ; return them as plain values
(+ 1 (raise 2))) ; => 2
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; 6. Mutation ;; 6. Mutation
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
; Use set! to assign a new value to an existing variable ;; Use `set!' to assign a new value to an existing variable
(define n 5) (define n 5)
(set! n 6) (set! n (add1 n))
n ; => 6 n ; => 6
; Many Racket datatypes can be immutable or mutable ;; Use boxes for explicitly mutable values (similar to pointers or
; (Pairs, Lists, Strings, Vectors, Hash Tables, etc...) ;; references in other languages)
(define n* (box 5))
(set-box! n* (add1 (unbox n*)))
(unbox n*) ; => 6
; Use "vector" to create a mutable vector ;; Many Racket datatypes are immutable (pairs, lists, etc), some come in
;; both mutable and immutable flavors (strings, vectors, hash tables,
;; etc...)
;; Use `vector' or `make-vector' to create mutable vectors
(define vec (vector 2 2 3 4)) (define vec (vector 2 2 3 4))
; Use vector-set! to update a slot (define wall (make-vector 100 'bottle-of-beer))
;; Use vector-set! to update a slot
(vector-set! vec 0 1) (vector-set! vec 0 1)
(vector-set! wall 99 'down)
vec ; => #(1 2 3 4) vec ; => #(1 2 3 4)
;; Create an empty mutable hash table and manipulate it
(define m3 (make-hash))
(hash-set! m3 'a 1)
(hash-set! m3 'b 2)
(hash-set! m3 'c 3)
(hash-ref m3 'a) ; => 1
(hash-ref m3 'd 0) ; => 0
(hash-remove! m3 'a)
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; 7. Modules ;; 7. Modules
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
; Modules let you organize code into multiple files and reusable libraries ;; Modules let you organize code into multiple files and reusable
;; libraries; here we use sub-modules, nested in the whole module that
;; this text makes (starting from the "#lang" line)
(module cake racket/base ; define a new module 'cake' based on racket/base (module cake racket/base ; define a `cake' module based on racket/base
(provide print-cake) ; function exported by the module (provide print-cake) ; function exported by the module
@ -368,90 +481,122 @@ vec ; => #(1 2 3 4)
(show " | ~a | " n #\space) (show " | ~a | " n #\space)
(show "---~a---" n #\-)) (show "---~a---" n #\-))
(define (show fmt n ch) ;; internal function (define (show fmt n ch) ; internal function
(printf fmt (make-string n ch)) (printf fmt (make-string n ch))
(newline))) (newline)))
; Use "require" to import all functions from the module ;; Use `require' to get all `provide'd names from a module
(require 'cake) (require 'cake) ; the ' is for a local submodule
(print-cake 3) (print-cake 3)
;(show "~a" 1 #\A) ; => error, "show" was not exported ; (show "~a" 1 #\A) ; => error, `show' was not exported
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; 8. Classes and Objects ;; 8. Classes and Objects
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
; Create a class fish% ;; Create a class fish% (-% is idomatic for class bindings)
(define fish% (define fish%
(class object% (class object%
(init size) ; initialization argument (init size) ; initialization argument
(super-new) ; superclass initialization (super-new) ; superclass initialization
; Field ;; Field
(define current-size size) (define current-size size)
; Public methods ;; Public methods
(define/public (get-size) current-size) (define/public (get-size)
(define/public (grow amt) (set! current-size (+ amt current-size))) current-size)
(define/public (eat other-fish) (grow (send other-fish get-size))))) (define/public (grow amt)
(set! current-size (+ amt current-size)))
(define/public (eat other-fish)
(grow (send other-fish get-size)))))
; Create an instance of fish% ;; Create an instance of fish%
(define charlie (define charlie
(new fish% [size 10])) (new fish% [size 10]))
; Use "send" to call an object's methods ;; Use `send' to call an object's methods
(send charlie get-size) ; => 10
(send charlie grow 6) (send charlie grow 6)
(send charlie get-size) ; => 16 (send charlie get-size) ; => 16
;; `fish%' is a plain "first class" value, which can get us mixins
(define (add-color c%)
(class c%
(init color)
(super-new)
(define my-color color)
(define/public (get-color) my-color)))
(define colored-fish% (add-color fish%))
(define charlie2 (new colored-fish% [size 10] [color 'red]))
(send charlie2 get-color)
;; or, with no names:
(send (new (add-color fish%) [size 10] [color 'red]) get-color)
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; 9. Macros ;; 9. Macros
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
; Macros let you extend the syntax of the language ;; Macros let you extend the syntax of the language
(define-syntax-rule (unless test then else)
(if test else then))
(unless (even? 10) "odd" "even") ; => "even" ;; Let's add a while loop
(define-syntax-rule (while condition body ...)
(let loop ()
(when condition
body ...
(loop))))
; Macros are hygienic, you cannot clobber existing variables! (let ([i 0])
(define-syntax-rule (swap x y) (while (< i 10)
(begin (displayln i)
(define tmp x) (set! i (add1 i))))
;; Macros are hygienic, you cannot clobber existing variables!
(define-syntax-rule (swap! x y) ; -! is idomatic for mutation
(let ([tmp x])
(set! x y) (set! x y)
(set! y tmp))) (set! y tmp)))
(define tmp 1) (define tmp 1)
(define a 2) (define a 2)
(define b 3) (define b 3)
(swap a b) (swap! a b)
(printf "tmp = ~a; a = ~a; b = ~a~n" tmp a b) ; tmp is unaffected by swap (printf "tmp = ~a; a = ~a; b = ~a\n" tmp a b) ; tmp is unaffected
;; But they are still code transformations, for example:
(define-syntax-rule (bad-while condition body ...)
(when condition
body ...
(bad-while condition body ...)))
;; this macro is broken: it generates infinite code, if you try to use
;; it, the compiler will get in an infinite loop
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; 10. Contracts ;; 10. Contracts
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
; Contracts impose constraints on values exported from modules ;; Contracts impose constraints on values exported from modules
(module bank-account racket (module bank-account racket
(provide (contract-out (provide (contract-out
[deposit (-> positive? any)] ; amount will always be a positive number [deposit (-> positive? any)] ; amounts are always positive
[balance (-> positive?)])) [balance (-> positive?)]))
(define amount 0) (define amount 0)
(define (deposit a) (set! amount (+ amount a))) (define (deposit a) (set! amount (+ amount a)))
(define (balance) amount) (define (balance) amount)
) )
(require 'bank-account) (require 'bank-account)
(deposit 5) (deposit 5)
(balance) ; => 5 (balance) ; => 5
; Any client that attempt to deposit a non-positive amount, will be blamed ;; Clients that attempt to deposit a non-positive amount are blamed
; (deposit -5) ; => deposit: contract violation ;; (deposit -5) ; => deposit: contract violation
; expected: positive? ;; expected: positive?
; given: -5 ;; given: -5
;; more details....
``` ```
## Further Reading ## Further Reading
Still up for more? Try [Quick: An Introduction to Racket with Pictures](http://docs.racket-lang.org/quick/) Still up for more? Try [Getting Started with Racket](http://docs.racket-lang.org/getting-started/)