You are on page 1of 3

Cheat Sheet CSI2132 Midterm

PROLOG
WHAT TO KNOW:
Logic Programming (progams =set of constraints, seeks all solutions)/Good for Meta Interpreters
Descriptive: describing known facts and relationships (or rules) about a specific problem
Specify Facts, Define rules, start queries and uses first order logic predicate symbols (equality, negation, logic
binary connections)
3- Arithmetic Expressions and I/O
Supported in Prolog : X+Y, X-Y, X*Y, X/Y, X // Y %integer division, X mod Y, X**Y , abs(X), ln(X) , sqrt(X)
X =:= Y % X equals Y, X =\= Y % X not equals Y, X < Y, X =< Y, X > Y, X >= Y
?- 1+2 = 1+2. true. ?- 3 = 1+2. false. ?- 1+2 = 2+1. false. ?- 3 is 1+2. true. ?- X is 1+2, X is 2+1. X = 3.
Power : pow( X, Y, Z ) :- Y > 1, Y1 is Y - 1, pow( X, Y1, Z1 ), Z is X * Z1. Or X**Y
Factorial: fact(0,1) as base case + fact(N, F) :- N > 0, N1 is N 1, fact(N1, F1), F is F1 * N.
Write/1: write(X). adds the value of X to the currently active output stream (by default the console). Read/1:
read(X) d X will be instantiated .
4 The Cut and Intro to List Processing
The Cut: ! - Goal that always succeeds and has a side effect (does not backtrack, seek to re-satisfy predicate)
Fail: fail - The fail predicate always fails. Combined with the Cut we get negation
not/1: not(x) Negation by failure. Prolog proofs the success of a goal not(F) by showing that it cannot satisfy F.
Remember that Prolog may also fail to proof F for trivial reasons, e.g., it may simply missing
facts in its database.
Not Equals or Difference: X=\= Y.
5 - List Representations & Processing
Representation: A list is represented by a particular tree with all the leaves of the tree on
branches to the left.
Dot operator: (X.Y) represents the head X (first element) and the tail Y of the list. (Needs
brackets [ ])
Accessing: use [head|tail] (ex : [st_john, moncton | [fredericton]] or [st_john | [moncton | [fredericton]]])
Member: Predicate member(X,L) : Recursive program member(X,[X|T]). member(X,[H|T]) :- member(X,T).
Insertion: listInsert(A,L,[A|L]). listInsert(A,[X|L], [X|LL]) :- listInsert(A,L,LL). (accumulate Lists in recurse)
Joining Lists: appendList([ ],Y,Y). appendList([A|B],Y,[A|W]) :- appendList(B,Y,W).
Length of List: listLength([],0). listLength([X|L],N) :- listLength(L,NN), N is NN+1.
6 More Examples
Findall/3: finds all possible Xs and puts in list in findall( X, condition, L). does not bind
variables
setof/3: setoff(Xs,Condition,L) finds all the solution and enters them in a list. eliminates
duplicates and sorts the result. Should be binded with ^
bagof(+Template, :Goal, -Bag) : Should be binded with ^. Similar to findall/3
7- Binary Trees and Graphs
Fact for a node: t(element, left, right) ( Ex: t(1,t(2,nil,nil),t(3,nil,nil)).)
Define a graph: graphA(X) :- X=g([a,b,c,d,e,f], [edge(a,b,3), edge(a,c,5), edge(a,d,7), edge(e,f,1), edge(d,f,6)]).\
SCHEME:
WHAT TO KNOW:
Functional Programming(program correspons to a function call/no loops & control statement/no variable &
assignments)/Good for games, symbolic computation, artificial intelligence, theorem proving.
Key Concept(conditons(if-then-else)/Functions as data types/Recursions/Variables as Pointers/automatic garbage
collection, lists and trees)
Interpreted language from LISP LISt Processor, continues to evolve, designed by MIT List is he
fundamental data structure
Programs start: (define ( blabla arg1 arg2) ..)
If statements (if (condition) (#t) (#f) ) or (if (condition) (#t) (if (condition) (#t) (#f)))
Conditions: cond ( ((condition) (#t)) ( (condition) (#t)) (else (#t)))
Let : temp value assignement (let ((a 3) (b 4)) (* a b) (+ a b) => 12 7
Let*: let* is similar to let but allows for sequential definitions. Same let/line variable changes.
Lists & stuff :

Cheat Sheet CSI2132 Midterm


Cons: itt puts the first expression as the head of the second
List: (list `a `b `c) => (a b c) ot (list `(a b c)) => ((a b
Define: (define square (lambda (x) (* x x))) ex: (square 2)
Lambda: ((lambda (x) (* x x)) 3) => 9
((let (var val) ) expr) ((lambda (var ) expr) val)
Store State in a Global with set!
Boolean comparison string: string=?, string<?, string>?, string<=?, string>=?
(symbol? x) true if x is a symbol
(number? x) true if x is a number
(eq? x y) true if x and y have internally
the same
representation (think of it as same pointer
value)
(equal? x y) true if x and y are identical
objects (not
necessarily atomic but same structure and
content)
(null? x) true if x is the empty lists ()

list expression
c))
(cons 1 2) => (1 . 2)
=> 4
(cons '(1 2) '(3 4)) =>
((1 2) 3 4)
(cons 2 '(3 4)) => (2 3 4)
(list 1 2 3) => (1 2 3)
(list '(1) '(2) '(3)) => ((1) (2)
(3))
(list '(a b c) '(d e f)) => ((a b
CAR: Content of the
Address Register ex:
(car '(a b c)) => a
(car '((a b) b c)) =>
(a b)
CDR: Content of the Decrement Register
ex: (cdr '(a b c)) => (b c) or (cdr '((a b)

b c)) => (b c)
Append List: (define (append-list L1 L2)
(if (null? L1)
L2
(cons (car L1) (append-list (cdr L1) L2))))
APPLY: apply proc arg1 ... args proc = procedure/args mustbe a list
ex: (apply +
(list 3 4))
==> 7
MAP: map proc list1 list2 ... lists = lists, proc = procedure = #args == #lists and
returning a single value.. Same length list. Applies proc per element and returns list
in order or evaluation.
TREE: ROOT = (car t) LEFT = (cadr t) RIGHT = (caddr t)
I/O : (display string), (read), (display (read))
DO: (do ((var init update) ...) (test resultIfTrue ...)
exprIfTestFalse...)
Ex:
(do ((i n (- i 1)) ; i=1, --I *NOTE* :inc/dec is done after a
fullloop.
(a1 1 (+ a1 a2)) ; a1=1, a1+=a2
(a2 0 a1))
; a2=0, a2=a1
or How I do it
((= i 1) a1)))))

(map cadr '((a b) (d e)


(g h)))
==> (b e h)
Vectors
(map (lambda (n)
Ex: (vector a b c) => #(a b c) or (define v (vector 1 (+ 1 2))) => v => #(1 3)
Or (vector-ref v 0) ; index starts at 0 => 1 or (vector-length v) => 2 or (vector-set! v 1 10) => #(1 10)(expt n n))
'(1 2 3 4 5))
==> (1 4 27
PYTHON
256 3125)
WHAT TO KNOW: Scripting language (dynamically typed (No variable declaration +Type checking at runtime.)/compiled at run time) Ex Tasks: search-and-replace over a large number of text files, rename and rearrange
multiple files. PYTHON = Multi-Paradigm (scripting + imperative (like C) + object-oriented (like Java) + functional
(like Scheme). Interpreted but compiled to byte code.
INTERPRETER: Enter simple command. Ex: use as a calculator >>> x=45 >>> x+2
47 or >>> 1+1 2 or >>>
type(3.14) <class 'float'>
Functions such a lists, ex: L1 = blab la L1.append(string),
L1.index(string), L1[0:-1], L1
More List: L1
PRINT: print uses the format print( value, , sep= , end=\n,
file=sys.stdout, flush=false)
>>> print(a) # a was set to "Hello World"
*NOTE * RANGES STOP 1 BEFORE ex: L1[0:3] goes to 2, blabla in range(10)
goes to 9
Create array: ex: studentId = {'Jane':10034566, 'Max':65998628,
'Robert':34566728 } and access
>>> 'Anna' in studentId : True
>>> studentId['Max'] : 65998628
If condition : (colon needed) or elif condition : or else :
While + for loops exist while contion : or for variable in sequence:
FILE : file = open('out.txt', 'w') and file.write(string + \n) and fid.close()
Import json to save any object to file use. Save json.dump(studentId,fid) or reload json.load(fid)
GO
WHAT TO KNOW: Imperative Language/Not quite object-oriented/No classes and inheritance/ But with interfaces
and forms of polymorphism

Cheat Sheet CSI2132 Midterm


Fundamental aspect of a functional programming Support for parallel, concurrent&systems programming and
performance computing
Go is designed to be the C of the 21 st century Go unifies conflicting language features Efficiency, speed
and safety of strongly typed languages (like C/C++ ) Fast compilation and building (like Java/C#) Ease of
programming of a dynamically typed language (as Python). Code is structured in packages
Starts: package main
PRINT: fmt.Printf("result= %f\n", m)
Import package: import package or import ( package1 package2 package3)
;
- semicolon required to use several statements in one line
Main: always a entry point ( main).. no arguments and return.. func main(){ fggdsdg}
FUNCTION: func keyword ex: func plusminus(a int, b int) (sum int, difference int)
VARIABLES: ex: var x int = 5 // global variable
or var ( // grouping or factoring the keyword a float64 = 8.8 b float64)
or u := 3.3 // intialized declaration
ARRAY: ex: var table = [5]int{3, 4, 8, 9, 2} SLICE: var slice []int = tableau[start:fin] ex: slice: := make([]int, 10,
100)
FOR LOOPS: NO WHILE OR DO or SWITCH case dg: case dgdsgd: case
for index, value := range collection
ex: tab [5]int for _, value := range tab{ gdgdgd }
for init; condition; post { ) or for condition { } or for { }
LAMBDA: func calc(p1 Point, p2 Point, d func(Point, Point)(float64))(float64)
DEFER: With defer the execution of a statement can be deferred to the end of a function or block. Ex. Defer
file.close
Goroutine :
go functionname()
Channels: ch1 := make(chan int) then put stuff in ch1 <- nb..then take
out nb2 = <- ch1
Interface:

You might also like