CS152
Chris Pollett
Nov 8, 2021
int i=5; float a = 3.2; a += i; //type coercion occurs
int a; //in a type we keep track of the type of a as being int 7.5; // when the compiler sees the expression // it recognizes a float literal 7 * 3.14; // determines 7 is an int literal, 3.14 is a float literal
Which of the following statements is true?
How can you do looping if you have a pure functional programming language?
for(int i=0; i <10; i++) {/*do something */} Seems to require variables; however, we can replace it with recursion: void my_for(int i, int stop, int step) { if ( i < stop) { /* do something */ my_for(i+ step, stop, step) } } my_for(0, 10, 1);
<expression> ::= <atom> | <list> <atom> ::= <number> | <string> | <identifier> | <character>| <boolean> <list> ::= '(' <expression-sequence> ')' <expression-sequence> ::= <expression> <expression-sequence> | <expression>
42 - a number "hello" - a string #t - a Boolean true #\a - the character 'a' (2.1 2.2 3.1) - a list of numbers a - an identifier hello - another identifier (+ 2 3) - a list consisting of the identifier "+" and two numbers (* (+ 2 3) (- 4 3) ) - a list consisting of an identifier and two lists
To evaluate expressions we use the rules:
(if (= a 0) (display "zero") (display "not zero")) ; display echoes to current output ; semicolon is used for comments cond (sorta like switch/case): (cond ((= a 0) (display "zero")) ((> a 0) (display "bigger than zero")) ((= a -1) (display "minus one")) (else (display "less than -1")))
(let ((a 2) (b 3)) (+ a b)) ; evaluates to 5
The define function can be used to add new associations between names and values in Scheme:
(define a 2) (define emptylist '()) (define (sum lo hi) ; could write: sum (lambda (lo hi) ... (if (= lo hi) lo (+ lo (sum (+ lo 1) hi))) )
Once something has been define can see its value are scheme prompt
>(sum 3 5) 12
(load "my-scheme-file.scm")
(import (my-library)) ; current folder my-library.scm or my-library.sls ;or (import (foo my-library)) ; ./foo/my-library.scm or ./foo/my-library.sls
(import (rnrs) (my-library))
(library (two-function) (export hello foo) ; these will be available outside library (import (rnrs)) (define (hello) (display "hello")) (define (foo) (display "foo")) (define (bob) (display "bob")) ; not available outside library )