Funkcije, neskončna zaporedja in java
|
|
- Joseph West
- 6 years ago
- Views:
Transcription
1 Funkcije, neskončna zaporedja in java LALGinar, 4. oktober 2013 Luka Fürst
2 Funkcijsko programiranje Funkcije kot osnovni gradniki funkcije kot argumenti funkcij funkcije, ki vračajo funkcije
3 Funkcijsko programiranje Funkcije kot osnovni gradniki funkcije kot argumenti funkcij funkcije, ki vračajo funkcije Sklicevalna preglednost (referential transparency) klic funkcije z določenim naborom vrednosti parametrov vedno vrne isti rezultat, ne glede na okoliščine klica posledica: odpor do spremenljivk (oz. stanja nasploh) predstavitev časovne variacije s seznami
4 Funkcijsko programiranje Funkcije kot osnovni gradniki funkcije kot argumenti funkcij funkcije, ki vračajo funkcije Sklicevalna preglednost (referential transparency) klic funkcije z določenim naborom vrednosti parametrov vedno vrne isti rezultat, ne glede na okoliščine klica posledica: odpor do spremenljivk (oz. stanja nasploh) predstavitev časovne variacije s seznami Leno vrednotenje objekt ovrednotimo šele tedaj, ko njegovo vrednost zares potrebujemo
5 Funkcijsko programiranje Funkcije kot osnovni gradniki funkcije kot argumenti funkcij funkcije, ki vračajo funkcije Sklicevalna preglednost (referential transparency) klic funkcije z določenim naborom vrednosti parametrov vedno vrne isti rezultat, ne glede na okoliščine klica posledica: odpor do spremenljivk (oz. stanja nasploh) predstavitev časovne variacije s seznami Leno vrednotenje objekt ovrednotimo šele tedaj, ko njegovo vrednost zares potrebujemo H. Abelson, G.J. Sussman, J. Sussman: Structure and Interpretation of Computer Programs (2. izdaja), MIT Press, 1996.
6 Funkcijsko programiranje in java Java ne ponuja konstruktov funkcijskega programiranja
7 Funkcijsko programiranje in java Java ne ponuja konstruktov funkcijskega programiranja Zanimiva in poučna pa je simulacija tovrstnih konstruktov v javi
8 Funkcijsko programiranje in java Java ne ponuja konstruktov funkcijskega programiranja Zanimiva in poučna pa je simulacija tovrstnih konstruktov v javi V javi lahko (do določene mere) programiramo po funkcijsko...
9 Funkcijsko programiranje in java Java ne ponuja konstruktov funkcijskega programiranja Zanimiva in poučna pa je simulacija tovrstnih konstruktov v javi V javi lahko (do določene mere) programiramo po funkcijsko......toda za ceno okorne in dolgovezne sintakse
10 Funkcije v javi Osnovo za predstavitev funkcij predstavljajo sledeči vmesniki: // zero-argument function interface F0<R> { R apply(); // one-argument function interface F1<P,R> { R apply(p param); // two-argument function interface F2<P1,P2,R> { R apply(p1 param1, P2 param2); // unary predicate interface Predicate<P> { boolean satisfies(p param);
11 Funkcije v javi Funkcijo predstavimo kot objekt tipa F0, F1, F2 ali Predicate class Square implements F1<Integer, Integer> { public Integer apply(integer a) { return (a * a); //... F1<Integer, Integer> sq = new Square(); System.out.println(sq.apply(5)); // 25
12 Funkcije v javi Funkcijo predstavimo kot objekt tipa F0, F1, F2 ali Predicate class Square implements F1<Integer, Integer> { public Integer apply(integer a) { return (a * a); //... F1<Integer, Integer> sq = new Square(); System.out.println(sq.apply(5)); // 25 Kot objekt brezimenskega implementatorja vmesnika: F1<Integer, Integer> sq = new F1<Integer, Integer>() { public Integer apply(integer a) { return (a * a); ; Več primerov: Scale, Plus, DivisibleBy
13 Funkcije, ki sprejemajo in/ali vračajo funkcije Kompozitum f g: public static <P,Q,R> F1<P,R> composition( final F1<Q,R> f, final F1<P,Q> g) { return new F1<P,R>() { public R apply(p param) { return f.apply(g.apply(param)); ; //... F1<Integer, Integer> sq = new Square(); F1<Integer, Integer> dbl = new Scale(2); F1<Integer, Integer> sqofdbl = composition(sq, dbl); F1<Integer, Integer> dblofsq = composition(dbl, sq); System.out.println(sqOfDbl.apply(3)); // 36 System.out.println(dblOfSq.apply(3)); // 18 Negacija predikata
14 Memoizacija Shranjevanje rezultatov funkcije pri določenih vrednostih Pri podanem naboru parametrov se funkcija izvede le enkrat V naslednjih klicih se uporabi shranjeni rezultat
15 Memoizacija Shranjevanje rezultatov funkcije pri določenih vrednostih Pri podanem naboru parametrov se funkcija izvede le enkrat V naslednjih klicih se uporabi shranjeni rezultat public static <P,R> F1<P,R> memoize(final F1<P,R> f) { return new F1<P,R>() { Map<P,R> memo = new HashMap<>(); ; public R apply(p param) { if (memo.containskey(param)) { return memo.get(param); R result = f.apply(param); memo.put(param, result); return result;
16 Seznami v javi Dve vrsti seznamov: prazen seznam seznam z glavo in repom glava je lahko karkoli, rep pa mora biti seznam abstract class List<T> { public abstract T head(); public abstract List<T> tail(); public abstract boolean isempty(); class Empty<T> extends List<T> { public T head() { throw new NoSuchElementException(); public List<T> tail() { throw new NoSuchElementException(); public boolean isempty() { return true;
17 Seznami v javi class Nonempty<T> extends List<T> { private T head; private List<T> tail; public Nonempty(T head, List<T> tail) { this.head = head; this.tail = tail; public T head() { return head; public List<T> tail() { return tail; public boolean isempty() { return false;
18 Tipične metode seznamov // returns the element at index ix public T get(int ix) { if (ix < 0) { throw new IllegalArgumentException("get: index < 0"); if (ix == 0) { return head(); return tail().get(ix-1); // returns a list comprising the elements indexed ixfirst,..., ixlast // of this list public List<T> sublist(int ixfirst, int ixlast) { if (ixfirst < 0 ixfirst > ixlast) { return new Empty<T>(); if (ixfirst == 0) { return new Nonempty<T>(head(), tail().sublist(0, ixlast-1)); return tail().sublist(ixfirst-1, ixlast-1);
19 Tipične metode seznamov // returns a new list obtained by applying func to individual elements // of this list public <U> List<U> map(f1<t,u> func) { if (isempty()) { return new Empty<U>(); return new Nonempty<U>( func.apply(head()), tail().map(func) ); // returns a list of all elements that satisfy the given predicate public List<T> filter(predicate<t> pred) { if (isempty()) { return new Empty<T>(); if (pred.satisfies(head())) { return new Nonempty<T>(head(), tail().filter(pred)); return tail().filter(pred);
20 Tipične metode seznamov // returns true iff any element satisfies the given predicate public boolean any(predicate<t> pred) { if (isempty()) { return false; if (pred.satisfies(head())) { return true; return tail().any(pred); // returns true iff all elements satisfy the given predicate public boolean all(predicate<t> pred) { if (isempty()) { return true; if (!pred.satisfies(head())) { return false; return tail().all(pred);
21 Tipične metode seznamov // returns func(...(func(func(initialvalue, [0]), [1]), [2]),..., [n]) public T leftfold(f2<t,t,t> func, T initialvalue) { if (isempty()) { return initialvalue; return tail().leftfold(func, func.apply(initialvalue, head())); // returns func([0], func([1], (... func([n], initialvalue)...))) public T rightfold(f2<t,t,t> func, T initialvalue) { if (isempty()) { return initialvalue; if (tail().isempty()) { return func.apply(head(), initialvalue); return func.apply(head(), tail().rightfold(func, initialvalue));
22 Motivacija Problem: poišči drugo praštevilo na intervalu [a, b]
23 Motivacija Problem: poišči drugo praštevilo na intervalu [a, b] Proceduralna rešitev: public static int secondprime(int a, int b) { int counter = 0, num = a; while (num <= b && counter < 2) { if (isprime(num)) counter++; num++; if (counter == 2) return (num-1); throw new NoSuchElementException();
24 Motivacija Problem: poišči drugo praštevilo na intervalu [a, b] Proceduralna rešitev: public static int secondprime(int a, int b) { int counter = 0, num = a; while (num <= b && counter < 2) { if (isprime(num)) counter++; num++; if (counter == 2) return (num-1); throw new NoSuchElementException(); Prepletanje naštevanja in preverjanja praštevilskosti
25 Motivacija Elegantnejša ( funkcijska ) rešitev: public static int secondprime(int a, int b) { Predicate<Integer> isprime =...; List<Integer> interval = List.intInterval(a, b); // [a,..., b] List<Integer> primes = interval.filter(isprime); return primes.get(1);
26 Motivacija Elegantnejša ( funkcijska ) rešitev: public static int secondprime(int a, int b) { Predicate<Integer> isprime =...; List<Integer> interval = List.intInterval(a, b); // [a,..., b] List<Integer> primes = interval.filter(isprime); return primes.get(1); Pomanjkljivosti postanejo očitne pri npr. a = 10 6, b = 10 7
27 Motivacija Elegantnejša ( funkcijska ) rešitev: public static int secondprime(int a, int b) { Predicate<Integer> isprime =...; List<Integer> interval = List.intInterval(a, b); // [a,..., b] List<Integer> primes = interval.filter(isprime); return primes.get(1); Pomanjkljivosti postanejo očitne pri npr. a = 10 6, b = 10 7 Rešitev: leni seznami
28 Leni seznami Alternativno ime: tokovi (streams) Enaka struktura kot pri navadnih seznamih Prvi element lenega seznama se ovrednoti že ob izdelavi Naslednji elementi se vrednotijo po potrebi
29 Leni seznami Abstraktni nadrazred in razred za prazen leni seznam sta definirana enako kot pri navadnih seznamih: class LazyList<T> { public abstract T head(); public abstract LazyList<T> tail(); public abstract boolean isempty(); class Empty<T> extends LazyList<T> { public T head() { throw new NoSuchElementException(); public LazyList<T> tail() {throw new NoSuchElementException(); public boolean isempty() { return true;
30 Neprazen leni seznam Rep je funkcija, ki se ovrednoti šele ob klicu metode tail class Nonempty<T> extends LazyList<T> { private T head; private F0<LazyList<T>> lazytail; public Nonempty(T head, F0<LazyList<T>> lazytail) { this.head = head; this.lazytail = memoize(lazytail); public T head() { return head; public LazyList<T> tail() { return lazytail.apply(); public boolean isempty() { return false;
31 Z navadnim seznamom: Celoštevilski interval [a, b] public static List<Integer> intinterval(int a, int b) { if (a > b) { return new Empty<Integer>(); return new Nonempty<Integer>(a, intinterval(a + 1, b)); Z lenim seznamom: public static LazyList<Integer> intinterval(final int a, final int b) { if (a > b) { return new Empty<Integer>(); return new Nonempty<Integer>(a, new F0<LazyList<Integer>>() { public LazyList<Integer> apply() { return intinterval(a + 1, b); );
32 Metoda filter pri lenih seznamih public LazyList<T> filter(final Predicate<T> pred) { if (isempty()) { return new Empty<T>(); if (pred.satisfies(head())) { return new Nonempty<T>(head(), new F0<LazyList<T>>() { public LazyList<T> apply() { return tail().filter(pred); ); return tail().filter(pred); Seznam se do prvega elementa, ki zadošča predikatu, preiskuje neučakano (eagerly) Po odkritju prvega takega elementa delo na seznamu počaka do zahteve po naslednjem ustreznem elementu
33 Drugo praštevilo na intervalu [a, b] public static int secondprime(int a, int b) { Predicate<Integer> isprime =...; LazyList<Integer> interval = LazyList.intInterval(a, b); LazyList<Integer> primes = interval.filter(isprime); return primes.get(1); Ob klicu metode filter se poišče samo prvo praštevilo Drugo praštevilo (in naslednja, če bi jih zahtevali) se poiščejo šele ob klicu metode get
34 Neskončni leni seznami Lene sezname lahko uporabimo za predstavitev neskončnih zaporedij
35 Neskončni leni seznami Lene sezname lahko uporabimo za predstavitev neskončnih zaporedij Seznam vseh naravnih števil: public static LazyList<Integer> ints() { return intsfrom(1); public static LazyList<Integer> intsfrom(final int n) { return new Nonempty<Integer>(n, new F0<LazyList<Integer>>() { public LazyList<Integer> apply() { return intsfrom(n+1); ); //... System.out.println(ints().sublist(0, 4)); // [1, 2, 3, 4, 5]
36 Neskončni leni seznami public static LazyList<Integer> makelist() { return gen(0, 1); private static LazyList<Integer> gen(final int a, final int b) { return new Nonempty<Integer>(a, new F0<LazyList<Integer>>() { public LazyList<Integer> apply() { return gen(b, a+b); );
37 Fibonaccijevo zaporedje public static LazyList<Integer> fibs() { return fibgen(0, 1); private static LazyList<Integer> fibgen(final int a, final int b) { return new Nonempty<Integer>(a, new F0<LazyList<Integer>>() { public LazyList<Integer> apply() { return fibgen(b, a+b); ); //... System.out.println(fibs().sublist(5, 9)); // [5, 8, 13, 21, 34]
38 Eratostenovo sito (postopek iskanja praštevil) Prični s seznamom [2, 3, 4,...] Dodaj prvi element seznama v seznam praštevil Odstrani prvi element seznama in vse njegove večkratnike Rekurzivno ponovi postopek na preostalem seznamu
39 Eratostenovo sito (postopek iskanja praštevil) Prični s seznamom [2, 3, 4,...] Dodaj prvi element seznama v seznam praštevil Odstrani prvi element seznama in vse njegove večkratnike Rekurzivno ponovi postopek na preostalem seznamu public static LazyList<Integer> primes() { return sieve(intsfrom(2)); private static LazyList<Integer> sieve(final LazyList<Integer> list) { return new Nonempty<Integer>( list.head(), new F0<LazyList<Integer>>() { public LazyList<Integer> apply() { return sieve( list.tail().filter( negate(new DivisibleBy(list.head()))) ); );
40 Neskončni leni seznami public static LazyList<Integer> seqa() { return new Nonempty<Integer>(1, new F0<LazyList<Integer>>() { public LazyList<Integer> apply() { return seqa(); );
41 Neskončni leni seznami [1,1,1,...]: public static LazyList<Integer> seqa() { return new Nonempty<Integer>(1, new F0<LazyList<Integer>>() { public LazyList<Integer> apply() { return seqa(); );
42 Neskončni leni seznami [1,1,1,...]: public static LazyList<Integer> seqa() { return new Nonempty<Integer>(1, new F0<LazyList<Integer>>() { public LazyList<Integer> apply() { return seqa(); ); public static LazyList<Number> seqb() { return new Nonempty<Number>(1, new F0<LazyList<Number>>() { public LazyList<Number> apply() { return add(seqa(), seqb()); );
43 Neskončni leni seznami [1,1,1,...]: public static LazyList<Integer> seqa() { return new Nonempty<Integer>(1, new F0<LazyList<Integer>>() { public LazyList<Integer> apply() { return seqa(); ); [1,2,3,...]: public static LazyList<Number> seqb() { return new Nonempty<Number>(1, new F0<LazyList<Number>>() { public LazyList<Number> apply() { return add(seqa(), seqb()); );
44 Neskončni leni seznami public static LazyList<Number> seqc() { return new Nonempty<Number>( 0, new F0<LazyList<Number>>() { public LazyList<Number> apply() { return new Nonempty<Number>( 1, new F0<LazyList<Number>>() { public LazyList<Number> apply() { return add(seqc(), seqc().tail()); ); );
45 Neskončni leni seznami Fibonaccijevo zaporedje: public static LazyList<Number> seqc() { return new Nonempty<Number>( 0, new F0<LazyList<Number>>() { public LazyList<Number> apply() { return new Nonempty<Number>( 1, new F0<LazyList<Number>>() { public LazyList<Number> apply() { return add(seqc(), seqc().tail()); ); );
46 Zaporedje približkov števila π π 4 =
47 Zaporedje približkov števila π π 4 = // successive approximations to pi public static LazyList<Number> pi() { return scale(partialsums(pisummands(1, 1)), 4); // [1, -1/3, 1/5, -1/7,...] private static LazyList<Number> pisummands(final int n, final int sign) { return new Nonempty<Number>( sign * 1.0 / n, new F0<LazyList<Number>>() { public LazyList<Number> apply() { return pisummands(n + 2, -sign); );
48 Zaporedje približkov števila π Zaporedje 4(1 1/3+1/5 1/7+...) počasi konvergira k π
49 Zaporedje približkov števila π Zaporedje 4(1 1/3+1/5 1/7+...) počasi konvergira k π Eulerjeva pohitritev: S n = S n+2 (S n+2 S n+1 ) 2 S n 2S n+1 +S n+2
50 Zaporedje približkov števila π Zaporedje 4(1 1/3+1/5 1/7+...) počasi konvergira k π Eulerjeva pohitritev: S n = S n+2 (S n+2 S n+1 ) 2 S n 2S n+1 +S n+2 public static LazyList<Number> euler(final LazyList<Number> list) { double s0 = list.get(0).doublevalue(); double s1 = list.get(1).doublevalue(); double s2 = list.get(2).doublevalue(); return new Nonempty<Number>( s2 - ((s2 - s1) * (s2 - s1)) / (s0-2 * s1 + s2), new F0<LazyList<Number>>() { public LazyList<Number> apply() { return euler(list.tail()); );
51 Zaporedje približkov števila π Leni seznam lenih seznamov: prvi seznam je izvorni seznam približkov drugi seznam je Eulerjeva pohitritev prvega tretji seznam je Eulerjeva pohitritev drugega...
52 Zaporedje približkov števila π Leni seznam lenih seznamov: prvi seznam je izvorni seznam približkov drugi seznam je Eulerjeva pohitritev prvega tretji seznam je Eulerjeva pohitritev drugega... public static LazyList<LazyList<Number>> eulerlistoflists( final LazyList<Number> list) { return new Nonempty<LazyList<Number>>( list, new F0<LazyList<LazyList<Number>>>() { public LazyList<LazyList<Number>> apply() { return eulerlistoflists(euler(list)); ); Zaporedje sestavimo iz prvih členov posameznih seznamov
53 Zaključek Vrednost lenih seznamov: elegantna formulacija neskončnih zaporedij enkapsulacija stanja (npr. zaporedja naključnih števil)
54 Zaključek Vrednost lenih seznamov: elegantna formulacija neskončnih zaporedij enkapsulacija stanja (npr. zaporedja naključnih števil) Java kot funkcijski jezik? Omogoča implementacijo nekaterih funkcijskih konceptov Okorna in dolgovezna sintaksa Pomanjkanje operacij za delo s seznami Pedagoška vrednost
Object-Oriented Design Lecture 13 CSU 370 Fall 2008 (Pucella) Friday, Oct 31, 2008
Object-Oriented Design Lecture 13 CSU 370 Fall 2008 (Pucella) Friday, Oct 31, 2008 Laziness For this lecture, I want to return to something that came up during the last homework, the third homework where
More informationComp 311 Functional Programming. Eric Allen, Two Sigma Investments Robert Corky Cartwright, Rice University Sağnak Taşırlar, Two Sigma Investments
Comp 311 Functional Programming Eric Allen, Two Sigma Investments Robert Corky Cartwright, Rice University Sağnak Taşırlar, Two Sigma Investments Streams Streams a form of lazy sequence inspired by signal-processing
More informationPrirejanje in preverjanje tipov
Uvod v C# Drugi del Dedovanje Sintaksa Prirejanje in preverjanje tipov Kaste preverjenih tipov Prekrivanje metod Dinamično povezovanje (poenostavljeno) Skrivanje Dinamično povezovanje (s skrivanjem) Fragile
More informationTransakcije v MariaDB/MySQL (transakcija A)
Transakcije v MariaDB/MySQL (transakcija A) Pomožni elementi In [1]: # pyodbc import pyodbc try: cn1.close() except: pass # MariaDB/MySQL conn = "DRIVER={MySQL ODBC 5.3 Unicode Driver};SERVER=localhost;DATABASE=sandbox;UID=tu
More informationDržavni izpitni center SPOMLADANSKI IZPITNI ROK *M * NAVODILA ZA OCENJEVANJE. Četrtek, 2. junij 2016 SPLOŠNA MATURA
Državni izpitni center *M16178113* SPOMLADANSKI IZPITNI ROK NAVODILA ZA OCENJEVANJE Četrtek, 2. junij 2016 SPLOŠNA MATURA RIC 2016 M161-781-1-3 2 IZPITNA POLA 1 1 1 2 1 3 3 4 1 5 3 6 2 7 1 8 1 9 1 10 3
More informationCollections and Combinatorial Search
Streams Collections and Combinatorial Search We ve seen a number of immutable collections that provide powerful operations, in particular for combinatorial search. For instance, to find the second prime
More informationProgramski jezik Java
Programski jezik Java Interno gradivo za predmet Algoritmi in programski jeziki (4. letnik) ArrayList (neprečiščeno besedilo) ArrayList Java class ArrayList(java.util.ArrayList) je hiter in za uporabo
More informationCollections, Maps and Generics
Collections API Collections, Maps and Generics You've already used ArrayList for exercises from the previous semester, but ArrayList is just one part of much larger Collections API that Java provides.
More informationStreams. CS21b: Structure and Interpretation of Computer Programs Spring Term, 2004
Streams CS21b: Structure and Interpretation of Computer Programs Spring Term, 2004 We ve already seen how evaluation order can change behavior when we program with state. Now we want to investigate how
More informationOsnove algoritmov in podatkovnih struktur I (OAPS I)
Univerza v Ljubljani Fakultetazaračunalništvo in informatiko Igor Rožanc Osnove algoritmov in podatkovnih struktur I (OAPS I) 2. letnik, VSP Računalništvo in informatika, vse smeri PROSOJNICE ZA 8. PREDAVANJA
More informationNavodila za interaktivne naloge Bober
Avtorji dokumenta: Dean Gostiša , Lovro Podgoršek Verzija dokumentacije: 1.1 Datum in kraj: 24. 7. 2013, Ljubljana Navodila za interaktivne naloge Bober Uvod 1.
More informationIP PACKET QUEUING DISCIPLINES AS BASIC PART OF QOS ASSURANCE WITHIN THE NETWORK
UDK621.3:(53+54+621 +66), ISSN0352-9045 Informacije MIDEM 39(2009)2, Ljubljana IP PACKET QUEUING DISCIPLINES AS BASIC PART OF QOS ASSURANCE WITHIN THE NETWORK Sasa Klampfer, Joze Mohorko, Zarko Cucej University
More informationInfinite Streams in Java
Infinite Streams in Java Dominik Gruntz Institute for Mobile and Distributed Systems University of Applied Sciences, Northwestern Switzerland Steinackerstrasse 5, CH-5210 Windisch, Switzerland dominik.gruntz@fhnw.ch
More informationCSC 1351 The Twelve Hour Exam From Hell
CSC 1351 The Twelve Hour Exam From Hell Name: 1 Arrays (Ch. 6) 1.1 public class L { int [] data ; void append ( int n) { int [] newdata = new int [ data. length +1]; for ( int i =0;i< data. length ;i ++)
More informationLambdas and Generics (Intro)
Lambdas and Generics (Intro) Dan S. Wallach and Mack Joiner, Rice University Copyright 2016 Dan S. Wallach, All Rights Reserved New this week in Subversion! week02-lists (check it out!) edu/rice/week2lists/glist.java
More informationVB komande. Programiranje 1
VB komande Programiranje 1 Zadatak 1: Sastaviti program koji se sastoji iz jedne ListBox kontrole, jedne Textbox kontrole i dva komandna dugmeta. Klikom na prvo komandno dugme umeće se u ListBox sadržaj
More informationPrinciples of Programming Languages
Principles of Programming Languages Slides by Yaron Gonen and Dana Fisman Based on Book by Mira Balaban and Lesson 20 Lazy Lists Collaboration and Management Dana Fisman www.cs.bgu.ac.il/~ppl172 1 Lazy
More informationPROGRAMIRANJE II: KONCEPTI PROGRAMSKIH JEZIKOV
1 U N I V E R Z A N A P R I M O R S K E M Fakulteta za matematiko, naravoslovje in informacijske tehnologije Iztok Savnik SKRIPTA ZA PREDMET PROGRAMIRANJE II: KONCEPTI PROGRAMSKIH JEZIKOV ŠTUDIJSKI PROGRAM
More informationCS 151. Linked Lists, Recursively Implemented. Wednesday, October 3, 12
CS 151 Linked Lists, Recursively Implemented 1 2 Linked Lists, Revisited Recall that a linked list is a structure that represents a sequence of elements that are stored non-contiguously in memory. We can
More informationFunctional Programming. Pure Functional Languages
Functional Programming Pure functional PLs S-expressions cons, car, cdr Defining functions read-eval-print loop of Lisp interpreter Examples of recursive functions Shallow, deep Equality testing 1 Pure
More informationFunctional Programming. Pure Functional Programming
Functional Programming Pure Functional Programming Computation is largely performed by applying functions to values. The value of an expression depends only on the values of its sub-expressions (if any).
More informationOrganization of Programming Languages CS3200/5200N. Lecture 11
Organization of Programming Languages CS3200/5200N Razvan C. Bunescu School of Electrical Engineering and Computer Science bunescu@ohio.edu Functional vs. Imperative The design of the imperative languages
More informationAn introduction to Scheme
An introduction to Scheme Introduction A powerful programming language is more than just a means for instructing a computer to perform tasks. The language also serves as a framework within which we organize
More informationHaskell: From Basic to Advanced. Part 2 Type Classes, Laziness, IO, Modules
Haskell: From Basic to Advanced Part 2 Type Classes, Laziness, IO, Modules Qualified types In the types schemes we have seen, the type variables were universally quantified, e.g. ++ :: [a] -> [a] -> [a]
More information... ; ako je a n parno. ; ako je a n neparno
Zadaci vezani za ciklus sa preduslovom (WHILE) Zad. Napisati program za izračunavanje n_tog stepena broja a. Zad2. Napisati program za izračunavanje sume S kvadrata parnih i kubova neparnih prirodnih brojeva
More information/*#include <iostream> // Prvi zadatak sa integralnomg ispita
/*#include // Prvi zadatak sa integralnomg ispita 27.01.2015 #include using std::setw; using std::cout; const int red(5), kolona(4); void unos(int[]); void ispis(int[][kolona]); float
More informationPublic-Service Announcements
Public-Service Announcements "CSUA has a Welcome BBQ on Wednesday, 2 September at 7PM in the Woz. Open to anyone interested in computer science. Please drop by our office located in 311 Soda Hall" Last
More informationCS Introduction to Data Structures Week 1 Thursday
CS 367 - Introduction to Data Structures Week 1 Thursday We assume that you are proficient at object-oriented programming in Java. Please enroll in CS300 if you do not know Java and have not written object-oriented
More informationProgramiranje Programski jezik C. Sadržaj. Datoteke. prof.dr.sc. Ivo Ipšić 2009/2010
Programiranje Programski jezik C prof.dr.sc. Ivo Ipšić 2009/2010 Sadržaj Ulazno-izlazne funkcije Datoteke Formatirane datoteke Funkcije za rad s datotekama Primjeri Datoteke komunikacija između programa
More informationData abstractions: ADTs Invariants, Abstraction function. Lecture 4: OOP, autumn 2003
Data abstractions: ADTs Invariants, Abstraction function Lecture 4: OOP, autumn 2003 Limits of procedural abstractions Isolate implementation from specification Dependency on the types of parameters representation
More informationUDF for volume calculation with the use of NTF method. Lastne Excel funkcije za izračun prostornin po NTF metodi
RMZ Materials and Geoenvironment, Vol. 54, No. 3, pp.419-425, 2007 419 UDF for volume calculation with the use of NTF method Lastne Excel funkcije za izračun prostornin po NTF metodi Mi l i v o j Vu l
More informationpojedinačnom elementu niza se pristupa imeniza[indeks] indeks od 0 do n-1
NIZOVI Niz deklarišemo navođenjemtipa elemenata za kojim sledi par srednjih zagrada[] i naziv niza. Ako je niz višedimenzionalni između zagrada[] se navode zarezi, čiji je broj za jedan manji od dimenzija
More informationAlgoritmi in podatkovne strukture 2. Urejanje (sorting)
Algoritmi in podatkovne strukture 2 Urejanje (sorting) osnove, metode deli in vladaj, kopica Andrej Brodnik: Algoritmi in podatkovne strukture 2 / Urejanje (sorting) osnove, metode deli in vladaj, kopica
More informationNormal Order (Lazy) Evaluation SICP. Applicative Order vs. Normal (Lazy) Order. Applicative vs. Normal? How can we implement lazy evaluation?
Normal Order (Lazy) Evaluation Alternative models for computation: Normal (Lazy) Order Evaluation Memoization Streams Applicative Order: evaluate all arguments, then apply operator Normal Order: pass unevaluated
More informationTehnike programiranja PREDAVANJE 2 Uvod v JavaScript
Tehnike programiranja PREDAVANJE 2 Uvod v JavaScript Predavanje 2 Ponovitev Predavanje 1 Naloge Uvod v JavaScript Pravila Primeri Priprava na laboratorijske vaje Pregled orodij ldos.fe.uni-lj.si >študij
More informationINSTRUCTIONS TO CANDIDATES
NATIONAL UNIVERSITY OF SINGAPORE SCHOOL OF COMPUTING FINAL ASSESSMENT FOR Semester 1 AY2017/2018 CS2030 Programming Methodology II November 2017 Time Allowed 2 Hours INSTRUCTIONS TO CANDIDATES 1. This
More informationUNIVERSITY OF CALIFORNIA Department of Electrical Engineering and Computer Sciences Computer Science Division. P. N. Hilfinger.
UNIVERSITY OF CALIFORNIA Department of Electrical Engineering and Computer Sciences Computer Science Division CS61B Fall 2007 P. N. Hilfinger Midterm Test READ THIS PAGE FIRST. Please do not discuss this
More informationUvod v evolucijsko računanje
Uvod v evolucijsko računanje Bogdan Filipič Odsek za inteligentne sisteme, Institut Jožef Stefan Jamova 39, 1000 Ljubljana bogdan.filipic@ijs.si Predavanje pri predmetih Umetna inteligenca 2 in Evolucijsko
More informationDelavnica za konfiguriranje dostopovnih točk Konfiguracija LANCOM L-54 z uporabo orodja LANConfig
Delavnica za konfiguriranje dostopovnih točk Konfiguracija LANCOM L-54 z uporabo orodja LANConfig Boštjan Lemut Prva povezava na L-54 s povezovalnim kablom povežemo mrežna vmesnika na računalniku in L-54
More information6.037 Lecture 7B. Scheme Variants Normal Order Lazy Evaluation Streams
6.037 Lecture 7B Scheme Variants Normal Order Lazy Evaluation Streams Edited by Mike Phillips & Ben Vandiver Original Material by Eric Grimson & Duane Boning Further Variations on a Scheme Beyond Scheme
More informationDelavnica za konfiguriranje dostopovnih točk WEB konfiguracija LANCOM L-54
Delavnica za konfiguriranje dostopovnih točk WEB konfiguracija LANCOM L-54 Boštjan Lemut Prva povezava na L-54 s povezovalnim kablom povežemo mrežna vmesnika na računalniku in L-54 v brskalniku vpišemo
More informationpublic static void negate2(list<integer> t)
See the 2 APIs attached at the end of this worksheet. 1. Methods: Javadoc Complete the Javadoc comments for the following two methods from the API: (a) / @param @param @param @return @pre. / public static
More informationImplementing a List in Java. CSE 143 Java. Just an Illusion? List Interface (review) Using an Array to Implement a List.
Implementing a List in Java CSE 143 Java List Implementation Using Arrays Reading: Ch. 13 Two implementation approaches are most commonly used for simple lists: Arrays Linked list Java Interface List concrete
More informationPublic-Service Announcements
Public-Service Announcements The Computer Science Undergraduate Association(CSUA) welcomes all students interested in computer science to join them at their Welcome BBQ on Saturday, 8/27 from 12-4pm at
More informationnamespace spojneice { public partial class Form1 : Form { public Form1() { InitializeComponent(); }
Spojnice using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Windows.Forms; using System.IO;
More informationpublic static boolean isoutside(int min, int max, int value)
See the 2 APIs attached at the end of this worksheet. 1. Methods: Javadoc Complete the Javadoc comments for the following two methods from the API: (a) / @param @param @param @return @pre. / public static
More informationFunctional Programming. Pure Functional Languages
Functional Programming Pure functional PLs S-expressions cons, car, cdr Defining functions read-eval-print loop of Lisp interpreter Examples of recursive functions Shallow, deep Equality testing 1 Pure
More informationfor i:=2 to n do if glasovi[i]>max then begin max:=glasovi[i]; k:=i {*promenljiva k ce cuvati indeks takmicara sa najvise glasova *} end;
{*Na Evroviziji je ucestvovalo n izvodjaca. Koji od njih je osvojio najvise glasova publike?*} program Evrovizija; glasovi:array[1..50] of integer; max,k:integer; writeln('unosi se broj izvodjaca:'); writeln('unose
More informationOsnove programskog jezika C# Čas 5. Delegati, događaji i interfejsi
Osnove programskog jezika C# Čas 5. Delegati, događaji i interfejsi DELEGATI Bezbedni pokazivači na funkcije Jer garantuju vrednost deklarisanog tipa. Prevodilac prijavljuje grešku ako pokušate da povežete
More informationCS115 - Module 3 - Booleans, Conditionals, and Symbols
Fall 2017 Reminder: if you have not already, ensure you: Read How to Design Programs, sections 4-5 Booleans (Bool) , and = are new functions, each of which produces a boolean value (Bool). (< 4 6)
More informationOrganizacija računalnikov (OR) UNI-RI, 3.l. RS Vaje. doc.dr. Mira Trebar
Organizacija računalnikov (OR) UNI-RI, 3.l. RS Vaje doc.dr. Mira Trebar 2 Vaja 1 (11.10.2010) Vaje so obvezne (delo v laboratoriju + doma) S1: Logisim MIPS procesor eno-cikelna izvedba ( logisim ) MIPS
More informationIntroduction to Functional Programming
Introduction to Functional Programming Xiao Jia xjia@cs.sjtu.edu.cn Summer 2013 Scheme Appeared in 1975 Designed by Guy L. Steele Gerald Jay Sussman Influenced by Lisp, ALGOL Influenced Common Lisp, Haskell,
More informationCS-140 Fall 2017 Test 2 Version A Nov. 29, 2017
CS-140 Fall 2017 Test 2 Version A Nov. 29, 2017 Name: 1. (10 points) For the following, Check T if the statement is true, the F if the statement is false. (a) T F : An interface defines the list of fields
More information// initialize array to true. for (i = 0; i < s; i++) f[i] = true; // get rid of known non-primes f[0] = f[1] = false;
Listing 1: GeneratePrimes.java This class Generates prime numbers up to a user specified maximum. The algorithm used is the Sieve of Eratosthenes. Eratosthenes of Cyrene, b. c. 276 BC, Cyrene, Libya
More informationStrukturirani poizvedovalni jezik SQL
Računalništvo Strukturirani poizvedovalni jezik SQL Danijel Skočaj, Evelin Vatovec Krmac Univerza v Ljubljani Fakulteta za pomorstvo in promet Literatura: Evelin Vatovec Krmac, Računalništvo in informatika,
More informationPREDMET. Osnove Java Programiranja. Čas JAVADOC
PREDMET Osnove Java Programiranja JAVADOC Copyright 2010 UNIVERZITET METROPOLITAN, Beograd. Sva prava zadržana. Bez prethodne pismene dozvole od strane Univerziteta METROPOLITAN zabranjena je reprodukcija,
More informationLinked List. ape hen dog cat fox. tail. head. count 5
Linked Lists Linked List L tail head count 5 ape hen dog cat fox Collection of nodes with a linear ordering Has pointers to the beginning and end nodes Each node points to the next node Final node points
More informationCS 320: Concepts of Programming Languages
CS 320: Concepts of Programming Languages Wayne Snyder Computer Science Department Boston University Lecture 04: Basic Haskell Continued o Polymorphic Types o Type Inference with Polymorphism o Standard
More informationChapter 15. Functional Programming Languages
Chapter 15 Functional Programming Languages Copyright 2009 Addison-Wesley. All rights reserved. 1-2 Chapter 15 Topics Introduction Mathematical Functions Fundamentals of Functional Programming Languages
More informationStreams, Delayed Evaluation and a Normal Order Interpreter. CS 550 Programming Languages Jeremy Johnson
Streams, Delayed Evaluation and a Normal Order Interpreter CS 550 Programming Languages Jeremy Johnson 1 Theme This lecture discusses the stream model of computation and an efficient method of implementation
More informationQuiz 1 (March 14, 2016)
MIT 6.005: Software Construction Max Goldman revised Sunday 13 th March, 2016, 15:30 Quiz 1 (March 14, 2016) Your name: Your Athena username: You have 50 minutes to complete this quiz. It contains 12 pages
More informationSolutions to Quiz 1 (March 14, 2016)
MIT 6.005: Software Construction Max Goldman revised Wednesday 16 th March, 2016, 14:08 Solutions to Quiz 1 (March 14, 2016) Problem 1 (Multiple Choice) (20 points). (a) Which of the following must be
More informationDM550 / DM857 Introduction to Programming. Peter Schneider-Kamp
DM550 / DM857 Introduction to Programming Peter Schneider-Kamp petersk@imada.sdu.dk http://imada.sdu.dk/~petersk/dm550/ http://imada.sdu.dk/~petersk/dm857/ ABSTRACT DATATYPES 2 Abstract Datatype (ADT)
More informationCOMP 410 Spring 2018 Midterm Practice Exam #2
COMP 410 Spring 2018 Midterm Practice Exam #2 Unification without Lists Consider each of the following unification attempts. If the unification succeeds, record any values any variables take. If the unification
More informationVodnik skozi Google Analytics Beta verzija 1. del. prehod s stare kode (urchin.js), k novi kodi za sledenje (ga.js)
Vodnik skozi Google Analytics Beta verzija 1. del prehod s stare kode (urchin.js), k novi kodi za sledenje (ga.js) Ta vodnik je povzetek Googe vodiča ' Tracking Code Migration Guide Switching from urchin.js
More informationAdministrivia. Last modified: Fri Aug 25 10:59: CS61B: Lecture #2 1
Administrivia Please make sure you have obtained a Unix account. If you are a concurrent enrollment student not yet on our lists, please tell a TA sothatwecanhaveyouaddedtothoseeligibletoreceiveanaccount.
More informationCPS 506 Comparative Programming Languages. Programming Language Paradigm
CPS 506 Comparative Programming Languages Functional Programming Language Paradigm Topics Introduction Mathematical Functions Fundamentals of Functional Programming Languages The First Functional Programming
More informationCS 3 Introduction to Software Engineering. 5: Iterators
CS 3 Introduction to Software Engineering 5: Iterators Questions? 2 PS1 Discussion Question You are to choose between two procedures, both of which compute the minimum value in an array of integers. One
More informationVežbe - XII nedelja PHP Doc
Vežbe - XII nedelja PHP Doc Dražen Drašković, asistent Elektrotehnički fakultet Univerziteta u Beogradu Verzija alata JavaDoc za programski jezik PHP Standard za komentarisanje PHP koda Omogućava generisanje
More informationControl Structure: Loop
Control Structure: Loop Knowledge: Understand the various concepts of loop control structure Skill: Be able to develop a program involving loop control structure 1 Loop Structure Condition is tested first
More informationInterfaces & Generics
Interfaces & Generics CSC207 Winter 2018 The Programming Interface The "user" for almost all code is a programmer. That user wants to know:... what kinds of object your class represents... what actions
More informationLjubljana,
Ljubljana, 9. 4. 2018 Katalog znanj in vzorci nalog za izbirni izpit za vpis na magistrski študij Računalništvo in informatika 2018/2019 0 KATALOG ZNANJ ZA IZBIRNI IZPIT ZA VPIS NA MAGISTRSKI ŠTUDIJ RAČUNALNIŠTVO
More informationQ: Do You made a backup before upgrade? A: Only cowards make backups!
Q: Do You made a backup before upgrade? You z malo - you A: Only cowards make backups! Real men don't use backups, they post their stuff on a public ftp server and let the rest of the world make copies.
More informationDefining Functions. CSc 372. Comparative Programming Languages. 5 : Haskell Function Definitions. Department of Computer Science University of Arizona
Defining Functions CSc 372 Comparative Programming Languages 5 : Haskell Function Definitions Department of Computer Science University of Arizona collberg@gmail.com When programming in a functional language
More informationProgrammazione Avanzata
Programmazione Avanzata Programmazione Avanzata Corso di Laurea in Informatica (L31) Scuola di Scienze e Tecnologie Programmazione Avanzata 1 / 51 Programming paradigms Programmazione Avanzata Corso di
More informationUnsupervised learning of scene and object planar parts
Elektrotehniški vestnik 74(5): 297 302, 2007 Electrotechnical Review, Ljubljana, Slovenija Unsupervised learning of scene and object planar parts Katarina Mele, Jasna Maver Univerza v Ljubljani, Fakulteta
More informationIzrada VI laboratorijske vježbe
Izrada VI laboratorijske vježbe 1. Programirati proceduru koja se aktivira sa Standard palete alatki klikom na button Fajlovi. Prilikom startovanja procedure prikazuje se forma koja sadrži jedan list box
More information3.2. CHOP-AND-EXPAND CONTEXT-FREE PARSER IN JAVA 39
3.2. CHOP-AND-EXPAND CONTEXT-FREE PARSER IN JAVA 39 3.2. Chop-and-Expand Context-Free Parser in Java In this section we present the two Java programs: List.java and CFParser.java, which realize the context-free
More informationMidterm #1. CMSC 433: Programming Language Technologies and Paradigms. October 14, 2013
Midterm #1 CMSC 433: Programming Language Technologies and Paradigms October 14, 2013 Name Instructions Do not start until told to do so! This exam has 10 double-sided pages (including this one); make
More informationSorting Algorithms part 1
Sorting Algorithms part 1 1. Bubble sort Description Bubble sort is a simple sorting algorithm. It works by repeatedly stepping through the array to be sorted, comparing two items at a time, swapping these
More informationRecursion and collections
1 Recursion and collections Recursion and Collections consider the problem of searching for an element in a list searching a list for a particular element can be performed by recursively examining the
More informationCS450 - Structure of Higher Level Languages
Spring 2018 Streams February 24, 2018 Introduction Streams are abstract sequences. They are potentially infinite we will see that their most interesting and powerful uses come in handling infinite sequences.
More informationStreams and Evalutation Strategies
Data and Program Structure Streams and Evalutation Strategies Lecture V Ahmed Rezine Linköpings Universitet TDDA69, VT 2014 Lecture 2: Class descriptions - message passing ( define ( make-account balance
More informationOsnove programskega jezika C
Rok Vrabič, Lovro Kuščer Osnove programskega jezika C Gradivo za vaje pri predmetih Mehatronski sistemi in Diskretni krmilni sistemi Ljubljana, 2014 Kazalo 0 Uvod... 1 1 Prvi C program... 2 1.1 Zgodovina
More informationb) program deljiv3; uses wincrt; var i:integer; begin i:=3; while i<100 do begin write(i:5); i:=i+3; end; end.
NAREDBA CIKLUSA SA PREDUSLOVOM WHILE 1.Odrediti vrednosti s i p nakon izvrsenja sledecih naredbi za dato a=43, a=34, a=105 program p1; var a,s,p:integer; write('unesite a:');readln(a); p:=a; s:=0; while
More informationBasics of Java: Expressions & Statements. Nathaniel Osgood CMPT 858 February 15, 2011
Basics of Java: Expressions & Statements Nathaniel Osgood CMPT 858 February 15, 2011 Java as a Formal Language Java supports many constructs that serve different functions Class & Interface declarations
More informationNaslavljanje v IP. Miran Meža
Naslavljanje v IP Miran Meža Omrežje vseh omrežij Avtonomni sistem Avtonomni sistem Avtonomni sistem Avtonomni sistem Avtonomni sistem Avtonomni sistem Omrežje vseh omrežij Usmerjanje prometa: poznati
More informationPost implementation steps for SAP Note:
Post implementation steps for SAP Note: 1945322 A. Text elements of REK-2 report 1. Run transaction SE38. 2. Fill in the Program field with value HSICRK28 3. Select Text elements radiobutton and click
More informationChapter 1. Fundamentals of Higher Order Programming
Chapter 1 Fundamentals of Higher Order Programming 1 The Elements of Programming Any powerful language features: so does Scheme primitive data procedures combinations abstraction We will see that Scheme
More informationCS111: PROGRAMMING LANGUAGE II
CS111: PROGRAMMING LANGUAGE II Computer Science Department Lecture 1(c): Java Basics (II) Lecture Contents Java basics (part II) Conditions Loops Methods Conditions & Branching Conditional Statements A
More informationBasic operators, Arithmetic, Relational, Bitwise, Logical, Assignment, Conditional operators. JAVA Standard Edition
Basic operators, Arithmetic, Relational, Bitwise, Logical, Assignment, Conditional operators JAVA Standard Edition Java - Basic Operators Java provides a rich set of operators to manipulate variables.
More information4. Object Structures, Aliasing, and Encapsulation
4. Object Structures, Aliasing, and Encapsulation Collaboration remark: The following slides are partly taken from the lecture Konzepte objektorientierter Programmierung by Prof. Peter Müller (ETH Zürich).
More informationSvi Java tipovi imaju ekvivalentan tip u jeziku Scala Većina Scala koda se direktno preslikava u odgovarajući Java konstrukt
Funkcionalno programiranje Interoperabilnost jezika Scala i Java Prevođenje u Java bajt kod Svi Java tipovi imaju ekvivalentan tip u jeziku Scala Većina Scala koda se direktno preslikava u odgovarajući
More informationCP222 Computer Science II. Linked Lists
CP222 Computer Science II Linked Lists Facebook data and Cambridge Analytica Tech News! Tech News! Facebook data and Cambridge Analytica Amazon now delivering Prime to car trunks Getting Help Fei CS Paraprof
More informationDefining Functions 1 / 21
Defining Functions 1 / 21 Outline 1 Using and Defining Functions 2 Implementing Mathematical Functions 3 Using Functions to Organize Code 4 Passing Arguments and Returning Values 5 Filter, Lambda, Map,
More informationCS 112 Introduction to Computing II. Wayne Snyder Computer Science Department Boston University
9/5/6 CS Introduction to Computing II Wayne Snyder Department Boston University Today: Arrays (D and D) Methods Program structure Fields vs local variables Next time: Program structure continued: Classes
More informationLambda-Related Methods Directly in Lists and Maps
coreservlets.com custom onsite training Lambda-Related Methods Directly in Lists and Maps Originals of slides and source code for examples: http://courses.coreservlets.com/course-materials/java.html Also
More information9/19/12. Why Study Discrete Math? What is discrete? Sets (Rosen, Chapter 2) can be described by discrete math TOPICS
What is discrete? Sets (Rosen, Chapter 2) TOPICS Discrete math Set Definition Set Operations Tuples Consisting of distinct or unconnected elements, not continuous (calculus) Helps us in Computer Science
More informationMatjaž Verbole. Algoritem D*
UNIVERZA V LJUBLJANI FAKULTETA ZA RAČUNALNIŠTVO IN INFORMATIKO Matjaž Verbole Algoritem D* DIPLOMSKO DELO NA UNIVERZITETNEM ŠTUDIJU Mentor: prof. dr. Borut Robič Ljubljana, 2012 Rezultati diplomskega dela
More information2/18/14. Uses for Discrete Math in Computer Science. What is discrete? Why Study Discrete Math? Sets and Functions (Rosen, Sections 2.1,2.2, 2.
Why Study Discrete Math? Sets and Functions (Rosen, Sections 2.1,2.2, 2.3) TOPICS Discrete math Set Definition Set Operations Tuples Digital computers are based on discrete units of data (bits). Therefore,
More information