Personal blog written from scratch using Node.js, Bootstrap, and MySQL. https://jrtechs.net
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

795 lines
17 KiB

5 years ago
  1. A quick review for CSCI-344 (Programming Language Concepts)
  2. # Ch #1 What are Programming Languages
  3. ## Types
  4. ### Imperative
  5. Most common type of language
  6. - Von Neumann (Fortran, Basic, C)
  7. - Object-oriented (SmallTalk, java)
  8. - Scripting (perl, python, basic)
  9. ### Declarative
  10. - Functional (Scheme, ML)
  11. - Logical (Prolog)
  12. ## Compilation vs Interpretation
  13. Interpretation is more flexible and gives better diagnostics for debugging.
  14. Compilation provides better performance.
  15. Often there is no clear cut difference between compilation and interpretation because many languages like java and python do a mix of the both.
  16. ### Compilation
  17. ![](media/plcfinal/compilation.png)
  18. ### Interpretation
  19. ![](media/plcfinal/interpretation.png)
  20. ### Mixed
  21. ![](media/plcfinal/mixed.png)
  22. ### Compilation Overview
  23. ![](media/plcfinal/compOverview.png)
  24. # Ch #2 Parsing
  25. ## Context-Free Grammars
  26. We use CFGs to produce a parse tree from tokens.
  27. ![](media/plcfinal/cfgEx.png)
  28. ## LL Grammar
  29. LL(1) grammar means that it is left right left most derivation parsing with one token look ahead.
  30. In practice we would use a stack to keep track what we expect to see.
  31. In this approach we would build the tree top down.
  32. The LL parsing algorithm uses FIRST/FOLLOW/PREDICT tables.
  33. Ex grammar:
  34. ![](media/plcfinal/ll.png)
  35. ## LR Grammar
  36. LR (Left to right right most derivation) builds the tree bottom up and is almost always table driven.
  37. ## Scanning
  38. A scanner is responsible for tokenizing the source, removing comments, saving text of identifiers, and saving line locations for error messages.
  39. A scanner is most naturally represented as a DFA (Deterministic Finite Automaton).
  40. ![](media/plcfinal/scanner.png)
  41. # Ch #10 Object Oriented
  42. Three major OO Components:
  43. - Encapsulation
  44. - Inheritance
  45. - Dynamic method binding
  46. Strict terms for OO lang: everything is an object, inheritance, dynamic method binding.
  47. Since java has primitives, it is not a true OO language.
  48. ## Small Talk
  49. Started as a thesis project in the 1960's, has been noted as being one of the best OO language historically.
  50. Basic coding examples on class-inheritance and constructors may be on exam.
  51. ### Syntax
  52. Excessively uses parenthesis.
  53. Method calls are in the form: (function:: object parameter1 parameter 2).
  54. NOTICE: the colons in the function name represents how many parameters it has.
  55. Also, there are no commas between parameters.
  56. Basic example class.
  57. ```scheme
  58. (class Shape Object
  59. (perimeter area) ; class-level parameters
  60. ;constructor
  61. (class-method initalize::shape (per ar)
  62. (init::shape (new self) per ar)
  63. )
  64. (method init::shape (per ar)
  65. (setPerimeter: self per)
  66. (setArea: self ar)
  67. self
  68. )
  69. (method getPerimeter ()
  70. perimeter
  71. )
  72. (method getArea ()
  73. area
  74. )
  75. (method setArea: (a)
  76. (set area a)
  77. )
  78. (method setPerimeter: (p)
  79. (set perimeter p)
  80. )
  81. )
  82. (val shape1 (initalize::shape Shape 12 5))
  83. ; area
  84. (getArea shape1)
  85. (setArea: shape1 88)
  86. (getArea shape1)
  87. ```
  88. Example with inheritance:
  89. ```scheme
  90. (class Circle Shape
  91. (radius)
  92. (class-method initalize:circle (rad)
  93. (init:circle (new self) rad)
  94. )
  95. (method init:circle (rad)
  96. (setRadius: self rad)
  97. self
  98. )
  99. (method setRadius: (rad)
  100. (set radius rad)
  101. (setArea: self (computeArea self))
  102. (setPerimeter: self (computePerimeter self))
  103. )
  104. (method getRadius ()
  105. radius
  106. )
  107. (method computeArea ()
  108. (*
  109. (asFloat (/ 22 7))
  110. (asFloat (squared radius))
  111. )
  112. )
  113. (method computePerimeter ()
  114. (*
  115. (asFloat 2)
  116. (*
  117. (asFloat (/ 22 7))
  118. (asFloat radius)
  119. )
  120. )
  121. )
  122. )
  123. (val circle1 (initalize:circle Circle 5))
  124. (getRadius circle1)
  125. (getArea circle1)
  126. (getPerimeter circle1)
  127. (setRadius: circle1 6)
  128. (getRadius circle1)
  129. (getArea circle1)
  130. (getPerimeter circle1)
  131. ```
  132. # Ch #3: Name, Scope, and Binding
  133. A name is a identifier. A binding links a name to an item.
  134. Scope is simply when a binding is active.
  135. # Binding
  136. Binding typically happens at two times:
  137. - Static: before run time
  138. - Dynamic: at run time.
  139. The earlier the binding the greater efficiency you have. The later the binding the greater flexibility you have.
  140. Static scope rules use the structure of the program.
  141. Dynamic scope rules depends on the current state of the program so, the function call sequences can change which bindings are active.
  142. # Lifetime
  143. Key events:
  144. - creation of object
  145. - creation of binding
  146. - references to variables (uses binding)
  147. - deactivation of binding (leave function stack)
  148. - reactivation of bindings
  149. - destruction of bindings
  150. - destruction of object
  151. If object out lives its binding it's garbage.
  152. If binding out lives its object it's a dangling reference.
  153. # Ch #4 Semantic Analysis
  154. The role of semantic analysis is to enforce semantic rules and generate a syntax tree(decorate the parse tree).
  155. To do this we use a attribute grammar.
  156. ex attribute grammar:
  157. ![](media/plcfinal/attributeGrammar.png)
  158. ## S-Grammar:
  159. Only uses synthesized attributes: the grammar above.
  160. ![](media/plcfinal/sgrammar.png)
  161. ## L-Grammar:
  162. A l attribute depends on things above them or besides them in the parse tree.
  163. ![](media/plcfinal/lgrammar.png)
  164. ## Action Routines
  165. Functions used to interleave the parser.
  166. # Ch #11: Functional Programming
  167. Examples:
  168. - Lisp
  169. - Scheme
  170. - FP
  171. - ML
  172. - Haskell
  173. Key Ideas:
  174. - everything is done by composing functions
  175. - no mutable state
  176. - no side effects
  177. - just produces a answer/result
  178. Necessary Features:
  179. - first class and high-order functions (takes in/returns functions)
  180. - polymorphism
  181. - powerful list functionality
  182. - structured function returns
  183. - fully general aggregates
  184. - garbage collection
  185. Since there is no state, it heavily relies on recursion to replace iteration.
  186. ## Scheme
  187. Not purely functional because it has some imperative stuff like assignment, I/O, sequencing and IO
  188. Scheme scopes:
  189. - let: calculates all RHS and then assign, can't use prior ones
  190. - let*: evaluates and then assigns
  191. - letrec: evaluates and then assign, this will loop back to fill in missing pieces as they are declared
  192. ### Scheme Examples:
  193. Note: cdr is tail of list and car is the first element in the list.
  194. ```scheme
  195. ; Computes length of list
  196. (define (length lst)
  197. (if (null? lst)
  198. 0
  199. (+
  200. 1
  201. (length (cdr lst))
  202. )
  203. )
  204. )
  205. ; determines if something is in the list
  206. ; returns:
  207. ; 1 if true(in list)
  208. ; 0 if not in list
  209. (define (inList lst n)
  210. (if (null? lst)
  211. 0
  212. (if (= n (car lst))
  213. 1
  214. (inList (cdr lst) n)
  215. )
  216. )
  217. )
  218. ; finds the sum of the list
  219. (define (sumList lst)
  220. (if (null? lst)
  221. 0 ; empty list
  222. (+
  223. (car lst)
  224. (sumList (cdr lst))
  225. )
  226. )
  227. )
  228. ```
  229. # Ch #6: Control Flow
  230. Types of iteration:
  231. - Sequencing: specifies a linear ordering on statements
  232. - Selection: selects a section of code ie: if statements
  233. - Iteration: for loops, iterates over a well-defined set
  234. - Concurrency
  235. - Exception Handling
  236. - Non-determinacy
  237. Orthogonality: feature can be used in any combination and the meaning is consistent.
  238. # Ch #7: Data Types
  239. Data types are a collection of values from a "domain".
  240. Data types specify the structure of the data and a collection of well-defined operations you can perform on that type.
  241. Data types are useful for implicit context and so that we can avoid meaningless operations.
  242. Strong typing is when language prevents on data that is not appropriate.
  243. Static typing is strong typing that the compiler can do.
  244. Orthogonality: no restriction on how a collection of features can be combined: like python lists.
  245. ## Type Systems
  246. A type system has rules for the following:
  247. - type equivalence
  248. - type compatibility: can type A be used in context of type B
  249. - type inference: type of expression given its operands types
  250. ## Type Checking
  251. Two major types:
  252. - Structural Equivalence: based on memory layout to determine if same -- can result in unintended equivalencies
  253. - Name equivalence: based on declaration type -- most common
  254. ## Coercion
  255. When an expression of one type is used in the context of another. Implicit coercion is when the language does it.
  256. Explicit is when the programmer does it (Casting).
  257. # Ch #12: Logical Programming
  258. Logical programming is based on predicate calculus.
  259. Important concepts:
  260. - Axioms: facts assumed true in knowledge base
  261. - Theorems: things that are provably true
  262. - Hypotheses: things or queries we would like to prove
  263. - ATOM is a constant like a number
  264. Within logical languages, statements can be written many ways.
  265. Logical languages are good for people but bad for people.
  266. Prolog uses backwards chaining to prove things true mathematically.
  267. A horn clause contains a HEAD and a BODY, sll statements must be in this term. The head is a single term, but, the body can be a list of terms.
  268. ## Prolog Ex
  269. ```Prolog
  270. path(b, f, 6).
  271. path(g, f, 3).
  272. path(e, g, 2).
  273. path(h, g, 4).
  274. % makes paths bi-directional
  275. biPath(A, B, Y) :- path(A, B, Y).
  276. biPath(A, B, Y) :- path(B, A, Y).
  277. % X is starting point
  278. % Y is ending point
  279. % P is a list of the points on the final path if one exists
  280. % N is the distance between X and Y if one exists
  281. % rule for terminal
  282. solveV(X, X, [X], 0, V).
  283. % recursively build out path
  284. solveV(A, B, [A|P], N, V) :- biPath(A, C, CC),
  285. \+member(C, V),
  286. solveV(C, B, P, CCC, [C|V]),
  287. N is CC + CCC.
  288. % expand given definition to helper function
  289. solve(A, B, P, N) :- solveV(A, B, P, N, [A]).
  290. % ex test runs in interpreter
  291. solve(h, c, P, N).
  292. solve(a, e, P, N).
  293. solve(g, c, P, N).
  294. solve(a, a, P, N).
  295. solve(g, h, P, N).
  296. ```
  297. # Ch #8: Composite Types
  298. Types:
  299. - Records (Structures)
  300. - Arrays
  301. - Strings
  302. - Pointers
  303. - Lists
  304. - File I/O
  305. ## Garbage Collection
  306. Problem with reference counter for garbage collection:
  307. ![](media/plcfinal/counter.png)
  308. Mark and Sweep solution:
  309. - Garbage collector walks heap basically marks everything as useless
  310. - starts at outside pointers marking everything it can get to as useful
  311. -walks the heap again placing useless items in the free queue.
  312. ## Pointers
  313. ### Tombstones
  314. Costly way of dealing with pointers references.
  315. This will create an additional object to maintain the pointer.
  316. ![](media/plcfinal/rip.png)
  317. ### Lock and Keys
  318. Makes sure that pointers and pointe contains the same lock value before you dereference the object.
  319. Note: this does not prevent attempting to use memory outside of your block resulting in a seg fault.
  320. ![](media/plcfinal/lock.png)
  321. # Ch #13: Erlang
  322. Approaches to parallel programming:
  323. - Synchronized access to shared memory
  324. - Message passing between processes (slower)
  325. Race conditions are whe the result depends on the order of the thread actions.
  326. Usually due to bad synchronization but, not always bad.
  327. Synchronization ensures that events in different processes happen in a desired order.
  328. Mutual exclusion: only one can access at a time.
  329. Condition synchronization: wait until some condition is true.
  330. Spin lock - busy-wait mutual exclusion, they waste processing cycles. Semaphores: widely used and uses a scheduler-based methods.
  331. Monitors are used to note who is in a critical region.
  332. ## Erlang
  333. Syntax of erlang is very similar to prolog with its pattern matching.
  334. Erlang relies on message passing for concurrency.
  335. Each process contains a "mailbox" where it can receive messages from.
  336. You process by listening for a message of a specific format: ie you can choose to ignore certain messages for a period of time.
  337. ### Examples
  338. ![](media/plcfinal/erlang.png)
  339. ```Erlang
  340. %%%-------------------------------------------------------------------
  341. %%% @author Jeffery Russell
  342. %%% @doc
  343. %%% PLC assignment 4
  344. %%% @end
  345. %%% Created : 16. Nov 2019
  346. %%%-------------------------------------------------------------------
  347. -module(prog4).
  348. -author("jeff").
  349. %% API
  350. -export([start/0, bank/0, client/0]).
  351. % helper function to spawn a specific amount
  352. % of clients
  353. spawn_client(N) when N >= 1 ->
  354. io:fwrite("Spawning a client\n"),
  355. spawn(prog4, client, []),
  356. spawn_client(N -1);
  357. spawn_client(_) ->
  358. io:fwrite("Spawned all clients\n").
  359. % start with random account balance between 2k-3k
  360. % receives message {clientid, number}
  361. % negatives removes from bank, positives add
  362. % returns {<client_id>, balance}
  363. bank() ->
  364. Balance = rand:uniform(1000) + 1999,
  365. io:format("Bank balance starting at: ~w~n", [Balance]),
  366. Client_count = rand:uniform(7) + 2,
  367. Client_left = 1,
  368. spawn_client(Client_count),
  369. loop(Balance, Client_count, Client_left).
  370. % main bank loop which listens for messages and
  371. % processes them
  372. loop(Balance, Client_count, Client_left) ->
  373. receive
  374. %io:format("Bank now has ~w", [balance])
  375. {CLIENT_ID, balance} ->
  376. io:fwrite("~w Requested Balance from the bank\n", [CLIENT_ID]),
  377. CLIENT_ID ! {Balance},
  378. loop(Balance, Client_count, Client_left);
  379. {CLIENT_ID, NUMBER} ->
  380. if
  381. Balance + NUMBER >= 0 ->
  382. CLIENT_ID ! {NUMBER, Balance + NUMBER, successful},
  383. loop(Balance + NUMBER, Client_count, Client_left);
  384. true ->
  385. CLIENT_ID ! {NUMBER, Balance, failed},
  386. loop(Balance, Client_count, Client_left)
  387. end;
  388. goodbye ->
  389. if
  390. Client_left == Client_count ->
  391. io:format("Bank is closing with balance ~w`\n", [Balance]);
  392. true ->
  393. loop(Balance, Client_count, Client_left + 1)
  394. end
  395. end.
  396. % helper function to fetch and print balance of the bank
  397. client_fetch_balance() ->
  398. bank_pid ! {self(), balance},
  399. receive
  400. {Balance} ->
  401. io:format("~w recieved the balance of ~w from the bank~n", [self(), Balance])
  402. end.
  403. % client process loop
  404. % if loop is increment of 5, it requests balance of bank
  405. % withdraws a random amount of money from mank
  406. % and prints the bank's response
  407. % after each withdrawl, it will sleep
  408. client_loop(LoopUntil, CurrentIndex) ->
  409. if
  410. CurrentIndex rem 5 == 0 ->
  411. client_fetch_balance();
  412. true -> pass
  413. end,
  414. if
  415. LoopUntil == CurrentIndex ->
  416. bank_pid ! goodbye,
  417. io:format("~w Client Finished\n", [self()]);
  418. true ->
  419. bank_pid ! {self(), 100-rand:uniform(199) },
  420. receive
  421. {Amount, Balance, Suc} ->
  422. io:format("~w recieved the balance of ~w from the bank after a ~w transation request of ~w~n", [self(), Balance, Suc, Amount])
  423. end,
  424. timer:sleep(rand:uniform(1000) + 499),
  425. client_loop(LoopUntil, CurrentIndex + 1)
  426. end.
  427. % creates random amount of clients
  428. client() ->
  429. Nums = rand:uniform(10) + 9,
  430. client_loop(Nums, 0).
  431. % spawns the bank
  432. start() ->
  433. register(bank_pid, spawn(prog4, bank, [])).
  434. ```
  435. # Ch #14: Scripting Languages
  436. Common Characteristics:
  437. - both batch and interactive use
  438. - easy to write high level expressions
  439. - simple scoping rules
  440. - flexible dynamic typing
  441. - easy access to other programs
  442. - sophisticated pattern matching and string manipulation
  443. - high level data types
  444. Often used to glue together other programs.
  445. Need to know bash on the exam.
  446. ## Bash
  447. ### Shall Parameters
  448. - "$#" is the number of parameters passed
  449. - "$0" is name of the script and its location in filesystem
  450. - "$1" is the first command line parameter. Goes up till 9
  451. - "$*" single word of all the parameters
  452. - "$@" array of all the parameters
  453. ex:
  454. ```bash
  455. if [ $# -eq 3 ];
  456. then
  457. if [ -f $1 ]
  458. then
  459. if [ -f $2 ]
  460. then
  461. encode_message $1 $2 $3
  462. else
  463. echo "File $2 does not exist"
  464. fi
  465. else
  466. echo "File $1 does not exist"
  467. fi
  468. else
  469. echo "Usage:"
  470. echo " encoder.sh <plane_text_file> <secret_key_file> <encoded_file>"
  471. fi
  472. ```
  473. ### Files
  474. ```bash
  475. while read line || [ -n "$line" ];
  476. do
  477. for word in $line
  478. do
  479. echo "$word"
  480. done
  481. done < "$1"
  482. ```
  483. ### Comparisons
  484. Numbers:
  485. - "-eq" equal
  486. - "-ge" greater than or equal
  487. - "-le" less than or equal
  488. - "-ne" not equal
  489. - "-gt" greater
  490. - "-lt" less
  491. ex:
  492. ```bash
  493. [n1 -eq n2]
  494. ```
  495. Strings:
  496. - "=" equal
  497. - "!=" not equal
  498. - "-n" length is greater than zero
  499. - "-z" length is equal to zero
  500. ex:
  501. ```
  502. [ s1 - s2 ]
  503. [ -n s1 ]
  504. ```
  505. Files:
  506. - "-d" path is a directory
  507. - "-f" is a file
  508. - "-e" file name exists
  509. - "-r" check of read permission
  510. - "-s" file has length greater than 0
  511. - "-w" write permission
  512. - "-x" execution permission
  513. ex:
  514. ```bash
  515. [ -d fname ]
  516. ```
  517. ### Control Flow
  518. #### If Statements
  519. ```bash
  520. if [ expression ];
  521. then
  522. statements
  523. elif [ expression ];
  524. then
  525. statements
  526. else
  527. statements
  528. fi
  529. ```
  530. #### Switch Statements
  531. ```bash
  532. case $var in
  533. val1)
  534. statements
  535. ;;
  536. val2)
  537. statements
  538. ;;
  539. *)
  540. statements
  541. ;;
  542. esac
  543. ```
  544. ### Math
  545. To do math you math like this:
  546. ```bash
  547. echo "$((124+23))"
  548. # or like this:
  549. VALOR=$[124+23]
  550. # or with let
  551. let X=124+23
  552. ```
  553. ### Functions
  554. Functions exist in bash.
  555. ```bash
  556. #!/bin/bash
  557. hello()
  558. {
  559. echo "Woeie"
  560. }
  561. hello # no parenthesis needed when calling
  562. # you can also declare functions with the keyword
  563. function check()
  564. {
  565. return 42
  566. }
  567. ```