Introduction to the Go Programming Language

Size: px
Start display at page:

Download "Introduction to the Go Programming Language"

Transcription

1 Introduction to the Go Programming Language Fabian Wenzelmann August 1, 2017 F. Wenzelmann Introduction to Go August 1, / 126

2 Why Go? What is Go? Go is a programming language developed at Google It is free and open source, available for Linux, Windows and Apple OS X Some buzzwords Compiled Statically typed Provides garbage collection Features concurrent programming F. Wenzelmann Introduction to Go August 1, / 126

3 Hello World package main import ( fmt ) f u n c main ( ) { fmt. P r i n t l n ( H e l l o World! ) Try on Go Playground: F. Wenzelmann Introduction to Go August 1, / 126

4 Installing Go I We will do some small exercises togehter, to follow this you need to install Go I recommend using Go 1.7 Follow instructions here: install from.tar Don t forget to set $GOPATH git clone in your src directory... or clone it somewhere and use docker: 1 docker-compose up 2 docker-compose exec golang /bin/bash F. Wenzelmann Introduction to Go August 1, / 126

5 Installing Go II Test your installation: go install golangsrc/examples/helloworld Execute /go/bin/helloworld (or whatever your gopath is) Most of the examples from the slides can be found in golangsrc/examples Exercise templates (most of them can t be compiled until you do the exercise) in golangsrc/exercises F. Wenzelmann Introduction to Go August 1, / 126

6 Toward Go 2 On July 13, 2017 Go version 2 was announced: There is a plan on how the developers will proceed Go 2 will be compatible with Go 1 code No fixed schedule yet F. Wenzelmann Introduction to Go August 1, / 126

7 Defining Functions Function definition with the func keyword The type of a variable / function comes after the variable name / function name You don t use a semicolon to end a statement f u n c IntMax ( a i n t, b i n t ) i n t { i f a > b { r e t u r n a e l s e { r e t u r n b Playground: F. Wenzelmann Introduction to Go August 1, / 126

8 Variables and Types Builtin Types Many types for ints and floats (numeric types) int8, int16, int32, int64: architecture-independent for n-bit integers There are also unsigned n-bit integers like uint8, uint16,... float32, float64 complex64, complex128 byte is an alias of uint8 bool predeclared constants true and false string is a sequence of bytes. We ll come to that later. Numeric Types When working with ints you usually work with the implementation-specific types int and uint which is either a 32 or 64 bit integer. F. Wenzelmann Introduction to Go August 1, / 126

9 Variables and Types Defining a Variable There are different ways of defining a variable: f u n c main ( ) { v a r i i n t = 21 v a r j i n t j = 42 k := 84 // s h o r t a s s i g n m e n t s t a t e m e n t fmt. P r i n t l n ( i, j, k ) Playground: Short assignment statements can be used inside function definitions, the type in this example is int. F. Wenzelmann Introduction to Go August 1, / 126

10 Variables and Types About Types and Conversions Go doesn t do automatic type conversions, you have to do it explictly int is a new type that is either int32 or int64, but it is not an alias for it! v a r i i n t 6 4 = 42 v a r j i n t = i cannot use i (type int64) as type int in assignment v a r j i n t = i n t ( i ) An exception is byte which is really an alias for uint8 F. Wenzelmann Introduction to Go August 1, / 126

11 Case Distinction If-Else and Switches I If-Else statements don t require parentheses, but braces are required You can only use type bool in if statements There is no thing like pythons elif, a switch statement is heavily used in Go f u n c RateNumber (num i n t ) { i f num == 42 { fmt. P r i n t l n ( The answer to e v e r y t h i n g ) e l s e i f num == 21 { fmt. P r i n t l n ( Only h a l f the t r u t h ) e l s e { fmt. P r i n t l n ( What a lame number ) F. Wenzelmann Introduction to Go August 1, / 126

12 Case Distinction If-Else and Switches II f u n c RateNumber (num i n t ) { s w i t c h num { c a s e 4 2 : fmt. P r i n t l n ( The answer to e v e r y t h i n g ) c a s e 2 1 : fmt. P r i n t l n ( Only h a l f the t r u t h ) d e f a u l t : fmt. P r i n t l n ( What a lame number ) Playground: F. Wenzelmann Introduction to Go August 1, / 126

13 Case Distinction About the Switch Statement I Switches work with many types, for example strings Cases are evaluated from top to bottom and the switch stops when a case succeeds If you want a fallthrough behaviour like in C++ use the fallthrough keyword at the end of the case If no variable is specified, a switch on the first case that evaluates to true is performed You can specifiy multiple values in one case, separated by comma F. Wenzelmann Introduction to Go August 1, / 126

14 Case Distinction About the Switch Statement II f u n c WakeUp( h i n t ) { s w i t c h { c a s e h < 1 1 : fmt. P r i n t l n ( Eeeew, t h a t e a r l y? ) c a s e h > 1 5 : fmt. P r i n t l n ( Had some fun l a s t n i g h t? ) d e f a u l t : fmt. P r i n t l n ( Seems p r e t t y normal to me. ) Playground: F. Wenzelmann Introduction to Go August 1, / 126

15 Loops The For Loop I There is only one statement in Go for a loop, for There are different variations of this statement: f u n c PrintNumbers ( s t a r t, end i n t ) { f o r i := s t a r t ; i < end ; i++ { fmt. P r i n t l n ( i ) Playground: F. Wenzelmann Introduction to Go August 1, / 126

16 Loops The For Loop II The init and post statements are optional Just put the ; there and leave the commands blank continue and break are supported f u n c F a c t o r i a l ( n u i n t ) u i n t { v a r r e s u i n t = 1 v a r i u i n t = 1 f o r ; i <= n ; i++ { r e s = i r e t u r n r e s Playground: F. Wenzelmann Introduction to Go August 1, / 126

17 Loops The For Loop III If you want something like a while loop use for with just a condition: f o r i < n { // your code h e r e For an infinite loop skip even that: f o r { // your code h e r e F. Wenzelmann Introduction to Go August 1, / 126

18 Loops Switches in a for-loop I Caution Be careful that the break statement breaks a switch statement as well as a for loop! So using break in a switch statement inside a for loop breaks the switch, not the for! F. Wenzelmann Introduction to Go August 1, / 126

19 Loops Switches in a for-loop II We want define a function that prints the first number i between start and end that is divisible by num The following code is wrong f u n c P r i n t D i v i s i b l e ( s t a r t, end, num i n t ) { f o r i := s t a r t ; i <= end ; i++ { s w i t c h { c a s e i%num == 0 : fmt. P r i n t f ( F i r s t number d i v i s i b l e by %d i s %d\n, num, i ) b reak Playground: F. Wenzelmann Introduction to Go August 1, / 126

20 Loops Switches in a for-loop III You have to create a label for breaking the loop in this case: f u n c P r i n t D i v i s i b l e ( s t a r t, end, num i n t ) { Loop : f o r i := s t a r t ; i <= end ; i++ { s w i t c h { c a s e i%num == 0 : fmt. P r i n t f ( F i r s t number d i v i s i b l e by %d i s %d\n, num, i ) b reak Loop Playground: F. Wenzelmann Introduction to Go August 1, / 126

21 Loops Switches in a for-loop IV The same problem with break occurs when using a select statement (later) When working with switches in loops it s usually a good idea to use a label and use break / continue with the label F. Wenzelmann Introduction to Go August 1, / 126

22 Loops Exercise Session 1 I Before we start the exercises: You should either copy the template from the exercises directory into mysolutions... or edit the template files directly, make sure to keep the directory structure Sample solutions are in solutions, but this spoils the fun The exercises are not very challenging, you should just get familiar with Go cd into the directory containing the.go file and compile with go build FILENAME.go This creates an executable called FILENAME F. Wenzelmann Introduction to Go August 1, / 126

23 Loops Exercise Session 1 II Exercise Template: exercises/prime (a) Implement a function I s P r i m e ( n u i n t ) b o o l that tests if n is prime number (b) In the main() function print the first 100 prime numbers F. Wenzelmann Introduction to Go August 1, / 126

24 Loops Exercise Session 1 III Exercise Template: exercises/exp Implement a method Exp ( x, e p s i l o n f l o a t 6 4 ) f l o a t 6 4 That computes e x with the following sum: e x = Stop when two consecutive sums differ by a value < ε where ε > 0. n=0 x n n! F. Wenzelmann Introduction to Go August 1, / 126

25 Strings, Arrays and Slices Arrays Arrays are very important, but you don t use them very often directly - instead you use slices An array of type T of size n is declared as var array [n]t Note that var array [n]t and var array [m]t are different types for n m The elements are initialized with a default value (0 for numbers) Access as in other languages: array[i] Example: F. Wenzelmann Introduction to Go August 1, / 126

26 Strings, Arrays and Slices Working With Arrays Arrays are not passed by reference, you ll always get a copy when passing it to a function / assigning an existing array to a variable Example: Instead of arrays you usually use a slice F. Wenzelmann Introduction to Go August 1, / 126

27 Strings, Arrays and Slices Slices I A slice describes a part of an array A slice of type T has the signature []T and it can be created from an array given the start and end position Don t pass a pointer to a slice, pass the array directly (this does not copy the content of the underlying array) Create a slice from an array with a[start:end] Chaning the value s[i] = something changes the value in the underlying array Example: F. Wenzelmann Introduction to Go August 1, / 126

28 Strings, Arrays and Slices Slices II You can also create a slice from an existing one and get / set an element out of a slice using the same notation as with arrays: v a r a r r a y [ 4 ] i n t a r r a y [ 0 ] = 1 a r r a y [ 1 ] = 2 a r r a y [ 2 ] = 3 a r r a y [ 3 ] = 4 s1 := a r r a y [ 1 : 4 ] s2 := s1 [ 1 : 2 ] fmt. P r i n t l n ( s2 ) fmt. P r i n t l n ( s1 [ 0 ] ) fmt. P r i n t l n ( s2 [ 0 ] ) Playground: F. Wenzelmann Introduction to Go August 1, / 126

29 Strings, Arrays and Slices Slices in Action A slice can be used as you use a vector in other programming languages You can append elements to a slice, if the underlying array is not big enough a new one will be allocated This especially means that if a slice grows bigger than its capacity you don t reference the same array as before! You can determine the size of a slice with len(s) A slice also has a capacity, which stores how much space the underlying array has: cap(s) Further reading: F. Wenzelmann Introduction to Go August 1, / 126

30 Strings, Arrays and Slices Slice Examples I To create an empty slice of type T you can use the make method: s := make ( [ ] i n t, 5) This will create a slice containing five elements (all 0) You can also specify the a capacity (the size of the underlying array): s := make ( [ ] i n t, 5, 10) The length of this slice is 5, but if you append another element there is no need to create a new array Example on Playground: F. Wenzelmann Introduction to Go August 1, / 126

31 Strings, Arrays and Slices Slice Examples II The append function appends an element to a slice and returns a new slice (remember that the array underneath can change) You can also pass more than one element to append s := make ( [ ] i n t, 1, 1) s = append ( s, 1) fmt. P r i n t l n ( s :, s ) s2 := s [ : ] s [ 0 ] = 21 s2 = append ( s2, 2, 3) fmt. P r i n t l n ( s2 :, s2 ) s [ 1 ] = 42 fmt. P r i n t l n ( s a f t e r m o d i f i c a t i o n o f s :, s ) fmt. P r i n t l n ( s2 a f t e r m o d i f i c a t i o n o f s :, s2 ) Try on the Playground: F. Wenzelmann Introduction to Go August 1, / 126

32 Strings, Arrays and Slices Iterating Over Slices You can iterate over a slice with for i := 0; i < len(s); i++ Or you can use the function range (more common): f o r i, v := range s { fmt. P r i n t f ( Element on p o s i t i o n %d i s %v\n, i, v ) An example on the Playground: If you re not interested in the position of an element name the variable There is an alternative method for creating a slice given an enumeration of its values: s := [ ] f l o a t 6 4 { 0. 5, , , 42.5 F. Wenzelmann Introduction to Go August 1, / 126

33 Strings, Arrays and Slices Strings The builtin type string is often used in the wrong way... For Go a string is just a (read-only) slice of bytes Go doesn t care if it is encoded in ASCII, UTF-8 or something else The notation str[k] returns the k-th byte in the string: v a r s t r s t r i n g = f o o bar fmt. P r i n t l n ( s t r ) fmt. P r i n t l n ( s t r [ 4 : ] ) fmt. P r i n t l n ( l e n ( s t r ) ) fmt. P r i n t l n ( s t r [ 1 ] ) Playground: F. Wenzelmann Introduction to Go August 1, / 126

34 Strings, Arrays and Slices Strings and UTF-8 strings are encoded in UTF-8: s t r := e fmt. P r i n t l n ( s t r ) fmt. P r i n t l n ( l e n ( s t r ) ) Playground: UTF-8 uses a different number of bytes, depending on the encoded char (e for example requires three bytes) So a for loop f o r i := 0 ; i < l e n ( s t r ) ; i++ {... should not be used to iterate over each character! F. Wenzelmann Introduction to Go August 1, / 126

35 Strings, Arrays and Slices rune Go uses a special type rune, which is an int32. This is a unicode codepoint The words character, codepoint etc. are used in an ambiguous way... What you know as a character in other languages can be thought of as a Go rune Rune constants are enclosed in single quotes in Go. For example 本 is mapped to the integer value (requires three bytes) Further reading: F. Wenzelmann Introduction to Go August 1, / 126

36 Strings, Arrays and Slices Using Strings You can concatenate strings with +: H e l l o + World We can also use the range function, this however treats strings in a special way! Instead of iterating over the bytes the function decodes one UTF-8 encoded rune in each iteration, the index of the loop is the starting position of the current rune. Note that some byte sequences are not valid UTF-8 points The package unicode/utf8 has some useful functions for working with strings and runes Other useful packages: 1 strings: Manipulate UTF-8 encoded strings 2 strconv: Conversion from and to basic types 3 regexp: Regular expressions F. Wenzelmann Introduction to Go August 1, / 126

37 Strings, Arrays and Slices Strings and Memory It s important to note that strings are just slices Therefor they refer to an array somewhere in the memory This can lead to memory problems: For example you load a big file in memory but you re only interested in some part of it If you get the part you re interested in by creating a slice or using some method from strings that only returns a slice of the existing string... the big array referenced by that slice will never be deleted by the garbage collection In such cases you should make a copy, use the copy function F. Wenzelmann Introduction to Go August 1, / 126

38 Other Basic Stuff Advanced Function Definitions I A function can have multiple return values (like tuples in python) and you can define multiple variables at once However there is no tuple type which you can use outside a function definition / variable initialization (kind of sad) A function can take an arbitrary number of arguments (of a certain type) Those elements are passed to the function as a slice F. Wenzelmann Introduction to Go August 1, / 126

39 Other Basic Stuff Advanced Function Definitions II f u n c MinMax ( a i n t, e l e m e n t s... i n t ) ( i n t, i n t ) { min, max := a, a f o r, v a l := range e l e m e n t s { s w i t c h { c a s e v a l < min : min = v a l c a s e v a l > max : max = v a l r e t u r n min, max Playground: F. Wenzelmann Introduction to Go August 1, / 126

40 Other Basic Stuff Advanced Function Definitions III A function that accepts multiple values like elements...int can also be called with a slice of that type: s := [ ] i n t {3, 2, 5, 1, 1 MinMax ( 1, s... ) Functions can be passed as arguments to functions and functions can return functions. Go also supports anonymous functions and closures F. Wenzelmann Introduction to Go August 1, / 126

41 Other Basic Stuff Advanced Function Definitions IV f u n c Chain ( f, g f u n c ( i n t ) i n t ) f u n c ( i n t ) i n t { r e t u r n f u n c ( n i n t ) i n t { r e t u r n f ( g ( n ) ) f u n c main ( ) { d o u b l e := f u n c ( n i n t ) i n t { r e t u r n 2 n addone := f u n c ( n i n t ) i n t { r e t u r n n + 1 fmt. P r i n t l n ( Chain ( double, addone ) ( 5 ) ) Playground: F. Wenzelmann Introduction to Go August 1, / 126

42 Other Basic Stuff Advanced Function Definitions V f u n c F i b o n a c c i ( ) f u n c ( ) u i n t { v a r a, b u i n t = 0, 1 r e t u r n f u n c ( ) u i n t { r e s := a a, b = b, a+b r e t u r n r e s f u n c main ( ) { f i b := F i b o n a c c i ( ) f o r i := 0 ; i < 1 5 ; i++ { fmt. P r i n t l n ( f i b ( ) ) Playground: F. Wenzelmann Introduction to Go August 1, / 126

43 Other Basic Stuff Exercise Session 2 I Exercise Template: exercises/mutliplyslice Implement a function M u l t i p l y S l i c e ( s [ ] i n t, num i n t ) [ ] i n t that repeats the slice s num times and returns the new slice. s := [ ] i n t {1, 2, 3 fmt. P r i n t l n ( M u l t i p l y S l i c e ( s, 3 ) ) [ ] F. Wenzelmann Introduction to Go August 1, / 126

44 Other Basic Stuff Exercise Session 2 II Exercise Template: exercises/palindrome Implement a function I s P a l i n d r o m e ( s s t r i n g ) b o o l that checks if s is a palindrome (ignoring cases). A palindrome is a string that reads the same backwards and forwards. Hint: Use []rune(s) to convert a string to a slice of runes. F. Wenzelmann Introduction to Go August 1, / 126

45 Other Basic Stuff Exercise Session 2 III Exercise Template: exercises/curry Implement a function Curry ( f f u n c ( x, y i n t ) i n t, x i n t ) f u n c ( y i n t ) i n t s.t. Curry(f, x)(y) evaluates to f(x, y). F. Wenzelmann Introduction to Go August 1, / 126

46 Other Basic Stuff Maps I The type map[keytype]valuetype implements dictionaries The KeyType is rather restricted, more information may be found here: However we can use int, string,... Short example: age := map [ s t r i n g ] i n t { Bob : 42, Susan : 21 age [ John ] = 84 fmt. P r i n t l n ( age [ Bob ] ) Playground: F. Wenzelmann Introduction to Go August 1, / 126

47 Other Basic Stuff Maps II Remove an entry for key (if this is not a valid key nothing will happen): d e l e t e ( age, Bob ) d e l e t e ( age, George ) F. Wenzelmann Introduction to Go August 1, / 126

48 Other Basic Stuff Maps III To check if a value exists you can use a two-value assignment Otherwise you get the default value of the value type agesusan, hassusan := age [ Susan ] agebob, hasbob := age [ Bob ] i f hassusan { fmt. P r i n t l n ( Age o f Susan i s, agesusan ) e l s e { fmt. P r i n t l n ( No e n t r y f o r Susan ) i f hasbob { fmt. P r i n t l n ( Age o f Bob i s, agebob ) e l s e { fmt. P r i n t l n ( No e n t r y f o r Bob ) Playground: F. Wenzelmann Introduction to Go August 1, / 126

49 Other Basic Stuff Maps IV Iterate over a map with range: f o r key, v a l u e := range age { fmt. P r i n t l n ( Age o f, key, i s, v a l u e ) Playground: It is safe to delete keys from a map while iterating over it with range Maps and slices are not safe to read / write concurrently from different goroutines, protect for example with a RWMutex F. Wenzelmann Introduction to Go August 1, / 126

50 Other Basic Stuff Pointers A pointer holds the memory address of a variable For a type T there is also a type *T The operator & generates a pointer from a variable, the operator * denotes the underlying value f u n c Swap ( a, b i n t ) { a, b = b, a f u n c main ( ) { a := 21 b := 42 Swap(&a, &b ) fmt. P r i n t l n ( a =, a, b =, b ) Playground: F. Wenzelmann Introduction to Go August 1, / 126

51 Other Basic Stuff nil The special type nil is what you know as null pointer from other languages Technically nil is not a type, nil can be used for different types such as pointers, slices, maps A slice can be nil and the slice functions will treat it as an empty slice So an empty slice can be defined like: v a r s [ ] i n t = n i l Or even just v a r s [ ] i n t F. Wenzelmann Introduction to Go August 1, / 126

52 Structs and Interfaces Structs Structs are used to group fields They don t work as classes as you know them from Java or other languages! You can define functions for your structs and they can be called with the dot notation F. Wenzelmann Introduction to Go August 1, / 126

53 Structs and Interfaces Defining Structs t y p e R e c t a n g l e s t r u c t { Width, Height f l o a t 6 4 f u n c ( r R e c t a n g l e ) Area ( ) f l o a t 6 4 { r e t u r n r. Width r. Height f u n c main ( ) { r1 := R e c t a n g l e {5, 10 r2 := R e c t a n g l e {Width : 10, Height : 20 fmt. P r i n t l n ( r1. Area ( ), r2. Area ( ) ) Playground: F. Wenzelmann Introduction to Go August 1, / 126

54 Structs and Interfaces Receivers Area is a so called pointer receiver, because the Rectangle object is passed by pointer In contrast a value receiver does not receive a pointer but an actual struct value However in this case a copy of the struct is created and passed to the function, thus changes made to the struct are not present in the object you called the method on In most cases pointer receivers are the best option Slices and Maps Note that slices, strings and maps must not be passed as pointers. They re lightweight structs. F. Wenzelmann Introduction to Go August 1, / 126

55 Structs and Interfaces Constructors I There is no such thing as a constructor in Go Instead for a struct T you usually define a method NewT(args) that returns a pointer to a new object: f u n c NewRectangle ( width, h e i g h t f l o a t 6 4 ) R e c t a n g l e { r e t u r n &R e c t a n g l e {Width : width, Height : h e i g h t F. Wenzelmann Introduction to Go August 1, / 126

56 Structs and Interfaces Constructors II You may have noticed the two different ways to create a new object: r1 := R e c t a n g l e {5, 10 r2 := R e c t a n g l e {Width : 10, Height : 20 The first one lists the elements in the order as defined in the struct definition, the second one uses name / value pairs The second one is much cleaner and easier to read! I don t know why this feature is not available for function calls... F. Wenzelmann Introduction to Go August 1, / 126

57 Structs and Interfaces Interfaces I An interface is a collection of method signatures You don t have to specify that a struct implements an interface, Go determines by itself if this is the case t y p e TwoDObject i n t e r f a c e { Area ( ) f l o a t 6 4 P e r i m e t e r ( ) f l o a t 6 4 Assuming we also defined the Perimeter function, a *Rectangle could be used as a TwoDObject F. Wenzelmann Introduction to Go August 1, / 126

58 Structs and Interfaces Interfaces II t y p e C i r c l e s t r u c t { Radius f l o a t 6 4 f u n c N e w C i r c l e ( r a d i u s f l o a t 6 4 ) C i r c l e { r e t u r n &C i r c l e { Radius : r a d i u s f u n c ( c C i r c l e ) Area ( ) f l o a t 6 4 { r e t u r n math. Pi c. Radius c. Radius f u n c ( c C i r c l e ) P e r i m e t e r ( ) f l o a t 6 4 { r e t u r n 2. 0 math. Pi c. Radius F. Wenzelmann Introduction to Go August 1, / 126

59 Structs and Interfaces Interfaces III f u n c P r i n t I n f o ( o b j e c t TwoDObject ) { fmt. P r i n t f ( TwoDObject : Area = %.3 f, P e r i m e t e r = %.3 f \n, o b j e c t. Area ( ), o b j e c t. P e r i m e t e r ( ) ) f u n c main ( ) { r := NewRectangle ( 5, 10) c := N e w C i r c l e ( 5 ) P r i n t I n f o ( r ) P r i n t I n f o ( c ) Complete code on Playground: F. Wenzelmann Introduction to Go August 1, / 126

60 Structs and Interfaces Interfaces IV Note that if you used a pointer receiver for type T to implement methods for an interface the type *T implements the interface, not T When using interfaces in functions you don t have to pass a pointer to that interface A variable of an interface type can have the value nil F. Wenzelmann Introduction to Go August 1, / 126

61 Structs and Interfaces Delegators I You can use delegators to delegate methods to another type: t y p e A s t r u c t { f u n c ( a A) Foo ( ) { fmt. P r i n t l n ( Foo on A ) a. Bar ( ) f u n c ( a A) Bar ( ) { fmt. P r i n t l n ( Bar on A ) t y p e B s t r u c t { A // d e l e g a t e methods to A f u n c ( b B) Bar ( ) { fmt. P r i n t l n ( Bar on B ) F. Wenzelmann Introduction to Go August 1, / 126

62 Structs and Interfaces Delegators II As seen before, all methods not defined in A and don t exist in B are delegated to the A instance Feels like overwriting and inheritance? It isn t! It s the so called composition pattern B is always of type B, and not of type A! Delegators are the same as storing an instance of that type in your struct and defining not implemented function and call the function on that element F. Wenzelmann Introduction to Go August 1, / 126

63 Structs and Interfaces Defining an Alias for a Type You can define a new type by defining it as something like an alias for that type t y p e I n t S e t map [ i n t ] s t r u c t { But it is a completely new type that only is something like an alias for map[int]interface You can define functions explictly for this type like f u n c ( s e t I n t S e t ) I n s e r t ( v a l i n t ) { s e t [ v a l ] = s t r u c t {{ Playground: F. Wenzelmann Introduction to Go August 1, / 126

64 Structs and Interfaces Consts There are different ways to define const values, see for details Usually you define something like c o n s t GolangHome = h t t p s : / / g o l a n g. org / c o n s t ( Red = r e d Blue = b l u e ) Playground: F. Wenzelmann Introduction to Go August 1, / 126

65 Structs and Interfaces Enum-like Types I Go doesn t support enum types Instead you usually define an alias of type int Go has an identifier iota that helps you generat sequences Details: We define an enumeration of all days of the week (though this is already done in the time package) F. Wenzelmann Introduction to Go August 1, / 126

66 Structs and Interfaces Enum-like Types II Define a const block and enumrate the possible values, use iota to enumerate the concrete values: t y p e Weekday i n t c o n s t ( Monday = Weekday ( i o t a ) Tuesday Wednesday Thursday F r i d a y Saturday Sunday ) F. Wenzelmann Introduction to Go August 1, / 126

67 Structs and Interfaces Enum-like Types III Define some new methods for our new type Hint: It is always useful to define a method String() string, this representation will be used by the print functions: f u n c ( day Weekday ) S t r i n g ( ) s t r i n g { s w i t c h day { c a s e Monday : r e t u r n Monday c a s e Tuesday : r e t u r n Tuesday... d e f a u l t : r e t u r n Unknown day Actually there is a tool for generating code for such types automatically, stringer F. Wenzelmann Introduction to Go August 1, / 126

68 Structs and Interfaces Enum-like Types IV Why the default case? In Go Weekday is just something like an alias for int You can still pass literals to a function that expects such a type (like an arbitrary integer in this example) This is however not so easy to understand, but is not needed that much You can read more about this here Full code example on the Playground: F. Wenzelmann Introduction to Go August 1, / 126

69 Structs and Interfaces Some Words About Types Go does not support generics There are some hacks : use interface{ and then cast to the appropriate type This is however not very clean But it can be really annoying to define types like IntSet and StringSet and leads to code duplication No (operator) overloading You can use different types for keys in a dictionary, but the behaviour is rather confusing: See the Comparison Operators in the language spec and the blog post about maps F. Wenzelmann Introduction to Go August 1, / 126

70 Structs and Interfaces Exercise Session 3 I Exercise Template: exercises/twodobject Implement a new type RightTriangle. Implement all the methods for TwoDObject and use a value receiver (either just save c or compute it from a and b). F. Wenzelmann Introduction to Go August 1, / 126

71 Structs and Interfaces Exercise Session 3 II Exercise Template: exercises/bintree Implement a type BinTree that implements a binary search tree and stores values of type int. Implement the following methods: NewBinTree ( ) BinTree Add ( elem i n t ) C o n t a i n s ( elem i n t ) b o o l F. Wenzelmann Introduction to Go August 1, / 126

72 Structs and Interfaces Errors I Go doesn t use try / catch exception handling Instead functions that could encounter errors use multiple return values Usually one of this return values is of type error: t y p e e r r o r i n t e r f a c e { E r r o r ( ) s t r i n g F. Wenzelmann Introduction to Go August 1, / 126

73 Structs and Interfaces Errors II New errors can be created with the package errors: e := e r r o r s. New( This i s an e r r o r ) Or if formatting is needed with the fmt package: e := fmt. E r r o r f ( I n d e x out o f bounds : %d, i ) Or of course you can create your own error type and implement the interface F. Wenzelmann Introduction to Go August 1, / 126

74 Structs and Interfaces Error Example I f u n c P a r s e I n t ( s t r s t r i n g ) { v a l, e r r := s t r c o n v. A t o i ( s t r ) i f e r r!= n i l { fmt. P r i n t l n ( E r r o r :, e r r ) e l s e { fmt. P r i n t l n ( Value i s, v a l ) f u n c main ( ) { P a r s e I n t ( 42 ) P a r s e I n t ( 4a ) Playground: F. Wenzelmann Introduction to Go August 1, / 126

75 Structs and Interfaces Error Example II There is also a special syntax for if statements that is used often in this context: f u n c P a r s e I n t ( s t r s t r i n g ) { i f v a l, e r r := s t r c o n v. A t o i ( s t r ) ; e r r!= n i l { fmt. P r i n t l n ( E r r o r :, e r r ) e l s e { fmt. P r i n t l n ( Value i s, v a l ) f u n c main ( ) { P a r s e I n t ( 42 ) P a r s e I n t ( 4a ) Playground: F. Wenzelmann Introduction to Go August 1, / 126

76 Structs and Interfaces Type Assertions I If you want to know which concrete type an interface value has you can perform a type check For example you may have a type that implements error and do something specific if a certain type is returned Note: This is not the normal way to do this in Go... F. Wenzelmann Introduction to Go August 1, / 126

77 Structs and Interfaces Type Assertions II t y p e A c c e s s D e n i e d E r r o r s t r u c t { protectedname s t r i n g f u n c ( e A c c e s s D e n i e d E r r o r ) E r r o r ( ) s t r i n g { r e t u r n fmt. S p r i n t f ( A c c e s s to %s d e n i e d, e. protectedname ) f u n c E v a l E r r ( e r r e r r o r ) { i f e r r == n i l { r e t u r n i f a c c e s s E r r, ok := e r r. ( A c c e s s D e n i e d E r r o r ) ; ok { fmt. P r i n t l n ( E v i l! C a l l i n g :, a c c e s s E r r ) e l s e { fmt. P r i n t l n ( e r r ) Playground: F. Wenzelmann Introduction to Go August 1, / 126

78 Structs and Interfaces Type Assertions III Can also be used in switch: f u n c P r e t t y ( a n y t h i n g i n t e r f a c e {) { s w i t c h v := a n y t h i n g. ( t y p e ) { c a s e i n t : fmt. P r i n t l n ( I n t :, v ) c a s e f l o a t 6 4, f l o a t 3 2 : fmt. P r i n t f ( F l o a t : %.2 f \n, v ) c a s e R e c t a n g l e : fmt. P r i n t f ( R e c t a n g l e : Width = %.2 f, Height = %.2 f \n, v. Width, v. Height ) d e f a u l t : fmt. P r i n t l n ( Something e l s e :, a n y t h i n g ) Playground: F. Wenzelmann Introduction to Go August 1, / 126

79 Structs and Interfaces Reading a File and the defer Statement I The defer statement is used to defer the execution of function call until the surrounding function returns In the following example we show how to read a file line by line Golang has an interface called io.reader, see GoDoc It has a single function: t y p e Reader i n t e r f a c e { Read ( p [ ] b y t e ) ( n i n t, e r r e r r o r ) Which reads up to len(p) bytes into p and returns the number of bytes read Often you don t read directly from a Reader but use a bufio.reader or bufio.scanner F. Wenzelmann Introduction to Go August 1, / 126

80 Structs and Interfaces Reading a File and the defer Statement II f u n c main ( ) { f, e r r := os. Open ( t e s t. t x t ) i f e r r!= n i l { fmt. P r i n t l n ( E r r o r opening f i l e :, e r r ) os. E x i t ( 1 ) d e f e r f. C l o s e ( ) s c a n n e r := b u f i o. NewScanner ( f ) f o r s c a n n e r. Scan ( ) { fmt. P r i n t l n ( s c a n n e r. Text ( ) ) i f e r r = s c a n n e r. E r r ( ) ; e r r!= n i l { fmt. P r i n t l n ( E r r o r w h i l e r e a d i n g f i l e :, e r r ) os. E x i t ( 1 ) F. Wenzelmann Introduction to Go August 1, / 126

81 Structs and Interfaces Reading a File and the defer Statement III In the above example we first opened the file with os.open(...) Once sucessfully opened we defer the call to the Close function, that s to say we wait until the surrounding function finishes and then close the file We create a bufio.scanner, by default this will scan for line breaks, but you may set a different split function See GoDoc Note You can use multiple defer statements, even with the same variable name. The deferred call s arguments are evaluated immediately. But the function call is not executed until the surrounding function returns! a a F. Wenzelmann Introduction to Go August 1, / 126

82 Structs and Interfaces Reading a File and the defer Statement IV There is also a mechanism called panic and recover We will not discuss it here, here s some reading: F. Wenzelmann Introduction to Go August 1, / 126

83 Concurrency in Go What is Concurrency Wikipedia Concurrent computing is a form of computing in which several computations are executed during overlapping time periods concurrently instead of sequentially (one completing before the next starts). Source: We may think of it as many things happening simultaneously Many languages and models today are not very good at expressing this view F. Wenzelmann Introduction to Go August 1, / 126

84 Concurrency in Go The go Statement Go is most popular for its mechanism for concurrent programming, it s very easy to write concurrent programs in Go It provides the go statement for running things concurrently And it also has an easy way to communicate between things happening concurrently Go was strongly influenced by the paper Communicating Sequential Processes by C. A. R. Hoare, first published 1985 Electronic version: Further reading on the Go blog: Don t confuse concurrency and parallelism! F. Wenzelmann Introduction to Go August 1, / 126

85 Concurrency in Go Concurrency vs. Parallelism In what follows there are some quotes from Rob Pike s wonderful video Concurrency Is Not Parallelism : Concurrency is a way of thinking and designing / structuring software The goal of concurrency is a good structure (Concurrency) Is the execution of independently executing processes Parallelism on the other hand is the simultaneous execution of multiple things, possibly related, possibly not Dealing with a lot of things at once, vs doing a lot of things at once But often parallelism helps you because things run faster (they don t have to) when you execute concurrent Go programs F. Wenzelmann Introduction to Go August 1, / 126

86 Concurrency in Go The go Statement - A Simple Example I The go statement starts a new goroutine and runs it concurrently It s as simple as this: Use go f(args) to run something concurrent, you don t wait for the routine to finish, you just start it and it does something for you A pretty easy example: f u n c main ( ) { go f u n c ( ) { f o r i := 0 ; i < 1 0 ; i++ { fmt. P r i n t l n ( i ) ( ) Playground: F. Wenzelmann Introduction to Go August 1, / 126

87 Concurrency in Go The go Statement - A Simple Example II If you run the program, what happens? You ll probably see nothing, as mentioned before a new goroutine starts, the current goroutine will not wait for another one to finish! Add time.sleep() and we should see something f u n c main ( ) { go f u n c ( ) { f o r i := 0 ; i < 1 0 ; i++ { fmt. P r i n t l n ( i ) ( ) time. S l e e p (2 time. Second ) Playground: F. Wenzelmann Introduction to Go August 1, / 126

88 Concurrency in Go The go Statement - A Simple Example III Of course using time.sleep is no proper way to wait for a goroutine to finish We need a way to communicate But first look at another simple example where we start multiple goroutines at once F. Wenzelmann Introduction to Go August 1, / 126

89 Concurrency in Go The go Statement - A Simple Example IV package main import ( fmt time ) f u n c main ( ) { f o r i := 0 ; i < 1 0 ; i++ { go f u n c ( v a l i n t ) { fmt. P r i n t l n ( v a l ) ( i ) time. S l e e p (2 time. Second ) Let s try it local, not in the Playground F. Wenzelmann Introduction to Go August 1, / 126

90 Concurrency in Go The go Statement - A Simple Example V You don t know in which order the goroutines are executed, so you get a more or less random sequence of outputs You can think of a goroutine as a lightweight thread, but it is not a thread as in other programming languages! Go will internally take care of everything, starting multiple threads on your OS for example goroutines are cheap. Of course they prodocue some overhead, but starting them is not very expensive. You can start even tens of thousands of such goroutines F. Wenzelmann Introduction to Go August 1, / 126

91 Concurrency in Go The go Statement - A Simple Example VI Why did we pass i as an argument to the function we started as a goroutine? If you don t pass an argument the functions uses i from the closure, but this closure is the same for all goroutines! This is a common mistake, you should always pass an argument to functions you start in a different goroutine inside a loop F. Wenzelmann Introduction to Go August 1, / 126

92 Concurrency in Go Introduction to Channels The most basic type for communicating between different goroutines are channels Think of them as conduits or assembly belts You can put an element of a certain type on the channel and receive an element from a channel They re safe for concurrent use, so many goroutines may write and read to / from a channel Go principle Do not communicate by sharing memory; instead, share memory by communicating. F. Wenzelmann Introduction to Go August 1, / 126

93 Concurrency in Go Unbuffered Channels I Create an (unbuffered) channel with make: c := make ( chan i n t ) This creates a channel in which you can write integer values For writing and receiving values there is the operator <- Write to channel: ch < 1 Read from channel: v := < ch F. Wenzelmann Introduction to Go August 1, / 126

94 Concurrency in Go Unbuffered Channels II f u n c main ( ) { ch := make ( chan i n t ) go f u n c ( ) { ch < 1 ( ) v := < ch fmt. P r i n t l n ( v ) Playground: Why is the write operation in a goroutine? Otherwise you get an error like fatal error: all goroutines are asleep - deadlock! This is because channels block F. Wenzelmann Introduction to Go August 1, / 126

95 Concurrency in Go Unbuffered Channels III The write operation blocks until the value is received by a read to that channel The read operation blocks until it reads a value from the channel This way you can synchronize goroutines I.e. they have to wait for each other to finish That leads to a simple pattern in Go: One goroutine waits for a read and one goroutine writes to that channel once it s finished F. Wenzelmann Introduction to Go August 1, / 126

96 Concurrency in Go Unbuffered Channels IV f u n c main ( ) { done := make ( chan b o o l ) // s t a r t a go r o u t i n e go f u n c ( ) { f o r i := 0 ; i < 1 0 ; i++ { fmt. P r i n t l n ( i ) // once done w r i t e to c h a n n e l done < t r u e ( ) // w a i t u n t i l g o r o u t i n e i s done < done Playground: F. Wenzelmann Introduction to Go August 1, / 126

97 Concurrency in Go Unbuffered Channels V After we start the goroutine we read from a channel - so the main goroutine blocks until a value on the channel appears The gouroutine first does some stuff and then informs the channel that it s done Let s look at a more complex example F. Wenzelmann Introduction to Go August 1, / 126

98 Concurrency in Go Computing the Minimum from a Slice of Ints I We want to compute the minimum from a slice of int values We will make some simplification and assume that the slice contains some elements Sequential approach: f u n c S l i c e M i n ( s [ ] i n t ) i n t { min := s [ 0 ] f o r, v := range s [ 1 : ] { i f v < min { min = v r e t u r n min F. Wenzelmann Introduction to Go August 1, / 126

99 Concurrency in Go Computing the Minimum from a Slice of Ints II Why don t we cut the slice into smaller pieces and run the method concurrent for all pieces? Use a channel to communicate the result of the concurrent methods F. Wenzelmann Introduction to Go August 1, / 126

100 Concurrency in Go Computing the Minimum from a Slice of Ints III f u n c main ( ) { s :=... n := l e n ( s ) ch := make ( chan i n t ) // s t a r t to go r o u t i n e s t h a t w r i t e t h e r e s u l t to ch go f u n c ( ) { ch < S l i c e M i n ( s [ : n / 2 ] ) () go f u n c ( ) { ch < S l i c e M i n ( s [ n / 2 : ] ) () res1 := < ch res2 := < ch i f res1 < res2 { fmt. P r i n t l n ( S m a l l e s t v a l u e :, r e s 1 ) e l s e { fmt. P r i n t l n ( S m a l l e s t v a l u e :, r e s 2 ) Playground: F. Wenzelmann Introduction to Go August 1, / 126

101 Concurrency in Go Does Parallelism Help? In the above example we have the hope that our concurrent approach helps to improve the execution time due to parallelism Another question: Why only use two pieces? Why not split into even more? Parallelism Parallelism may help to improve your runtime, but this does not mean that a concurrent approach is always faster! Gos aim is to provide clear structured code via concurrency, not to improve your runtime using parallelism, but often enough this is the case! F. Wenzelmann Introduction to Go August 1, / 126

102 Concurrency in Go Buffered Channels Until now we ve only seen unbuffered channels Provide the buffer size as the second argument to make to create an unbuffered channel ch := make ( chan i n t, 10) Sends block only when the buffer is full, reads when the channel is empty Example: Coordinate n workers that work concurrently F. Wenzelmann Introduction to Go August 1, / 126

103 Concurrency in Go range and Closing Channels I If it is unkown how many arguments you have to read from a channel, you can use range ch to iterate over all its values This reads until the channel gets closed by close(ch) Example: Read values from a search of unkown size You can also close a channel and still retrieve the remaining results F. Wenzelmann Introduction to Go August 1, / 126

104 Concurrency in Go range and Closing Channels II f u n c main ( ) { ch := make ( chan i n t ) go f u n c ( ) { f o r i := 0 ; i < 1 0 ; i++ { ch < i c l o s e ( ch ) ( ) f o r v a l := range ch { fmt. P r i n t l n ( v a l ) Playground: F. Wenzelmann Introduction to Go August 1, / 126

105 Concurrency in Go Read / Write Channels If you want to signal that a function only reads / writes to a channel you can use the type chan<- string for a channel were strings can be written <-chan string for a channel were strings can be read F. Wenzelmann Introduction to Go August 1, / 126

106 Concurrency in Go Running Multiple goroutines I Sometimes you need to run multiple goroutines that don t return anything / don t write to a channel In this case you can use a WaitGroup from the sync package F. Wenzelmann Introduction to Go August 1, / 126

107 Concurrency in Go Running Multiple goroutines II f u n c dosomething ( ) { time. S l e e p ( time. Second 3) f u n c main ( ) { v a r wg sync. WaitGroup wg. Add ( 5 ) f o r i := 0 ; i < 5 ; i++ { go f u n c ( ) { d e f e r wg. Done ( ) dosomething ( ) ( ) wg. Wait ( ) Playground: F. Wenzelmann Introduction to Go August 1, / 126

108 Concurrency in Go Running Multiple goroutines III With wg.add(n) you add n events to wait for After all our go routines are started you use wg.wait(). This operation blocks until the counter reaches zero A call to wg.done() reduces the counter by one If you have to dynmaically Add new values make sure that the counter can t reach zero until you call Add This means usually: calls to Add should execute before the statement creating the goroutine or other event to be waited for F. Wenzelmann Introduction to Go August 1, / 126

109 Concurrency in Go Running Multiple goroutines IV Make sure to always call wg.done defer is a good way to achieve this Read the doc for more details F. Wenzelmann Introduction to Go August 1, / 126

110 Concurrency in Go Exercise Session 4 I Exercise Template: exercises/matrix Implement matrix multiplication for two matrices A R n m and B R m k. In the template you ll find an implementation that doesn t use concurrency. Improve this implementation by starting a goroutine for each row in A and in this goroutine starts a new goroutine for each column in B. The main function creates some big matrices and compares the execution time of both implementations. F. Wenzelmann Introduction to Go August 1, / 126

111 Concurrency in Go Exercise Session 4 II Exercise Template: exercises/bintree Go has no iterator interface. There are two common approaches: 1 Implement a function that writes all values in a channel 2 Implement a function that accepts a function and applies a function to all values in the collection Implement both approaches for your BinTree type. Both versions should iterate the values sorted. I t e r a t e V a l u e s ( ch chan< i n t ) Apply ( f f u n c ( v a l i n t ) ) Implement the following with those methods (choose one or do both) 1 Print all values 2 Build the sum of all values F. Wenzelmann Introduction to Go August 1, / 126

112 Testing and Benchmarking The package testing The package testing provides method for testing and benchmarking your code For details see the documentation here Put your tests in a different package, i.e. create a directory tests Create files ending in test.go To test function X write a method TestX(t *testing.t) To benchmark function X write a method BenchmarkX(b *testing.b) F. Wenzelmann Introduction to Go August 1, / 126

113 Testing and Benchmarking Testing and Benchmarking Example I f u n c F a c t o r i a l ( n u i n t ) u i n t { v a r r e s u i n t = 1 v a r i u i n t = 1 f o r ; i <= n ; i++ { r e s = i r e t u r n r e s f u n c F a c t o r i a l R e c ( n u i n t ) u i n t { i f n == 0 { r e t u r n 1 e l s e { r e t u r n n F a c t o r i a l R e c ( n 1) F. Wenzelmann Introduction to Go August 1, / 126

114 Testing and Benchmarking Testing and Benchmarking Example II f u n c T e s t F a c t o r i a l ( t t e s t i n g.t) { v a l u e s := [ ] u i n t {0, 1, 2, 3 r e s u l t s := [ ] u i n t {1, 1, 2, 6 f o r i := 0 ; i < l e n ( v a l u e s ) ; i++ { f := f a c t o r i a l. F a c t o r i a l ( v a l u e s [ i ] ) i f f!= r e s u l t s [ i ] { t. E r r o r f ( Expected %d! = %d, got %d, v a l u e s [ i ], r e s u l t s [ i ], f ) F. Wenzelmann Introduction to Go August 1, / 126

115 Testing and Benchmarking Testing and Benchmarking Example III Change to the directory examples/factorial/tests Run go test: PASS ok golangsrc/examples/factorial/tests 0.001s Add a false entry in the tests and run again: test FAIL: TestFactorial (0.00s) factorial test.go:15: Expected 3! = 7, got 6 FAIL exit status 1 FAIL golangsrc/examples/factorial/tests 0.001s F. Wenzelmann Introduction to Go August 1, / 126

116 Testing and Benchmarking Testing and Benchmarking Example IV f u n c B e n c h m a r k F a c t o r i a l ( b t e s t i n g. B) { f o r i := 0 ; i < b.n; i++ { f a c t o r i a l. F a c t o r i a l ( 2 0 ) f u n c B e n c h m a r k F a c t o r i a l R e c ( b t e s t i n g. B) { f o r i := 0 ; i < b.n; i++ { f a c t o r i a l. F a c t o r i a l R e c ( 2 0 ) F. Wenzelmann Introduction to Go August 1, / 126

117 Testing and Benchmarking Testing and Benchmarking Example V Run go test -bench=. BenchmarkFactorial ns/op BenchmarkFactorialRec ns/op F. Wenzelmann Introduction to Go August 1, / 126

118 Testing and Benchmarking Further Reading Official documentation 5-simple-tips-and-tricks-for-writing-unit-tests-in-golang go-testing-part-1-vanillla F. Wenzelmann Introduction to Go August 1, / 126

119 Web Programming The Package http The http package provides HTTP client and server implementations Golang is designed for web programming When writing a server each request is handled in its own goroutine We can t discuss everything here, but we ll look at a small example context is a very useful package, but not discussed here F. Wenzelmann Introduction to Go August 1, / 126

120 Web Programming Further Web Libraries There are connectors for may database types, Go has its own SQL package You require a driver for a certain database type, for example MYSQL, postgres, sqlite,... Also Redis, Memcached,... I haven t found a suitable thing like Django for python But Gorilla offers a lot of stuff CSRF Sessions Secure Cookies... More extensive example: F. Wenzelmann Introduction to Go August 1, / 126

121 Web Programming Templates Instead of writing your output directly to the ResponseWriter you can use templates This are files in which you can use variables, call functions etc. A bit like Django templates For more details see build-web-application-with-golang/en/07.4.html and F. Wenzelmann Introduction to Go August 1, / 126

122 Organzing Your Go Code Where to Put Your Go Code Usually all your Go code is in one src directory, usually in a directory go in your home Put your own code in a directory github.com/youraccount/yourpackage A package contains multiple source files, each file must have package line package PACKAGENAME You can add subpackages, but for small project this is sufficient Add a cmd directory and a subdirectory for each command For example if you have an executable helloworld, add cmd/helloworld/helloworld.go This file must have package main and a function main() F. Wenzelmann Introduction to Go August 1, / 126

123 Organzing Your Go Code Function and Struct Names Functions, Interfaces, Structs,... that begin with a capital letter are exported, i.e. can be used in other packages Everything that starts with a lowercase letter can only be used inside your package You should also format your Go code with gofmt helloworld.go or gofmt PACKAGE This shows you how the could should look like, add -w to apply the formatting directly to your file See Plugins for Go are available for popular editors like vim, Atom,... F. Wenzelmann Introduction to Go August 1, / 126

124 Organzing Your Go Code Installing Third Party Packages Use go get github.com/..., for example to install the MySQL driver: gogetgithub.com/go-sql-driver/mysql Use go install github.com/... to also compile the main files See F. Wenzelmann Introduction to Go August 1, / 126

125 Organzing Your Go Code Documenting Your Code Document each function / struct / interface with a comment starting with the name: // HelloWorld p r i n t s H e l l o World to the s t a n d a r d output f u n c HelloWorld ( ) { fmt. P r i n t l n ( H e l l o World ) If you upload your code to github.com your documentation can be found on godoc.org You can also run godoc locally: godoc -http=:6060 and then visit F. Wenzelmann Introduction to Go August 1, / 126

126 The End Thanks for Listening! Do you have any questions or feedback? F. Wenzelmann Introduction to Go August 1, / 126

Go Tutorial. Ian Lance Taylor. Introduction. Why? Language. Go Tutorial. Ian Lance Taylor. GCC Summit, October 27, 2010

Go Tutorial. Ian Lance Taylor. Introduction. Why? Language. Go Tutorial. Ian Lance Taylor. GCC Summit, October 27, 2010 GCC Summit, October 27, 2010 Go Go is a new experimental general purpose programming language. Main developers are: Russ Cox Robert Griesemer Rob Pike Ken Thompson It was released as free software in November

More information

ITI Introduction to Computing II

ITI Introduction to Computing II (with contributions from R. Holte) School of Electrical Engineering and Computer Science University of Ottawa Version of January 11, 2015 Please don t print these lecture notes unless you really need to!

More information

ITI Introduction to Computing II

ITI Introduction to Computing II (with contributions from R. Holte) School of Electrical Engineering and Computer Science University of Ottawa Version of January 9, 2019 Please don t print these lecture notes unless you really need to!

More information

Google Go illustrated on the basis of Fibonacci numbers

Google Go illustrated on the basis of Fibonacci numbers Google Go illustrated on the basis of Fibonacci numbers Jan Pennekamp RWTH University Aachen Chair for Data Management and Data Exploration Prof. Dr. T. Seidl Supervision: Dipl.-Ing. Marwan Hassani Friday,

More information

#29: Logarithm review May 16, 2009

#29: Logarithm review May 16, 2009 #29: Logarithm review May 16, 2009 This week we re going to spend some time reviewing. I say re- view since you ve probably seen them before in theory, but if my experience is any guide, it s quite likely

More information

Computer Science Introductory Course MSc - Introduction to Java

Computer Science Introductory Course MSc - Introduction to Java Computer Science Introductory Course MSc - Introduction to Java Lecture 1: Diving into java Pablo Oliveira ENST Outline 1 Introduction 2 Primitive types 3 Operators 4 5 Control Flow

More information

Python. chrysn

Python. chrysn Python chrysn 2008-09-25 Introduction Structure, Language & Syntax Strengths & Weaknesses Introduction Structure, Language & Syntax Strengths & Weaknesses Python Python is an interpreted,

More information

Clojure Concurrency Constructs, Part Two. CSCI 5828: Foundations of Software Engineering Lecture 13 10/07/2014

Clojure Concurrency Constructs, Part Two. CSCI 5828: Foundations of Software Engineering Lecture 13 10/07/2014 Clojure Concurrency Constructs, Part Two CSCI 5828: Foundations of Software Engineering Lecture 13 10/07/2014 1 Goals Cover the material presented in Chapter 4, of our concurrency textbook In particular,

More information

Lab 2: Static Response, Cantilevered Beam

Lab 2: Static Response, Cantilevered Beam Contents 1 Lab 2: Static Response, Cantilevered Beam 3 1.1 Objectives.......................................... 3 1.2 Scalars, Vectors and Matrices (Allen Downey)...................... 3 1.2.1 Attribution.....................................

More information

Python & Numpy A tutorial

Python & Numpy A tutorial Python & Numpy A tutorial Devert Alexandre School of Software Engineering of USTC 13 February 2012 Slide 1/38 Table of Contents 1 Why Python & Numpy 2 First steps with Python 3 Fun with lists 4 Quick tour

More information

Lecture 8 HASHING!!!!!

Lecture 8 HASHING!!!!! Lecture 8 HASHING!!!!! Announcements HW3 due Friday! HW4 posted Friday! Q: Where can I see examples of proofs? Lecture Notes CLRS HW Solutions Office hours: lines are long L Solutions: We will be (more)

More information

INTRODUCTION. This is not a full c-programming course. It is not even a full 'Java to c' programming course.

INTRODUCTION. This is not a full c-programming course. It is not even a full 'Java to c' programming course. C PROGRAMMING 1 INTRODUCTION This is not a full c-programming course. It is not even a full 'Java to c' programming course. 2 LITTERATURE 3. 1 FOR C-PROGRAMMING The C Programming Language (Kernighan and

More information

1 Trees. Listing 1: Node with two child reference. public class ptwochildnode { protected Object data ; protected ptwochildnode l e f t, r i g h t ;

1 Trees. Listing 1: Node with two child reference. public class ptwochildnode { protected Object data ; protected ptwochildnode l e f t, r i g h t ; 1 Trees The next major set of data structures belongs to what s called Trees. They are called that, because if you try to visualize the structure, it kind of looks like a tree (root, branches, and leafs).

More information

Lecture 4: Constructing the Integers, Rationals and Reals

Lecture 4: Constructing the Integers, Rationals and Reals Math/CS 20: Intro. to Math Professor: Padraic Bartlett Lecture 4: Constructing the Integers, Rationals and Reals Week 5 UCSB 204 The Integers Normally, using the natural numbers, you can easily define

More information

INF 4140: Models of Concurrency Series 3

INF 4140: Models of Concurrency Series 3 Universitetet i Oslo Institutt for Informatikk PMA Olaf Owe, Martin Steffen, Toktam Ramezani INF 4140: Models of Concurrency Høst 2016 Series 3 14. 9. 2016 Topic: Semaphores (Exercises with hints for solution)

More information

Introduction to Python

Introduction to Python Introduction to Python Luis Pedro Coelho luis@luispedro.org @luispedrocoelho European Molecular Biology Laboratory Lisbon Machine Learning School 2015 Luis Pedro Coelho (@luispedrocoelho) Introduction

More information

Proof Techniques (Review of Math 271)

Proof Techniques (Review of Math 271) Chapter 2 Proof Techniques (Review of Math 271) 2.1 Overview This chapter reviews proof techniques that were probably introduced in Math 271 and that may also have been used in a different way in Phil

More information

4.4 The Calendar program

4.4 The Calendar program 4.4. THE CALENDAR PROGRAM 109 4.4 The Calendar program To illustrate the power of functions, in this section we will develop a useful program that allows the user to input a date or a month or a year.

More information

( )( b + c) = ab + ac, but it can also be ( )( a) = ba + ca. Let s use the distributive property on a couple of

( )( b + c) = ab + ac, but it can also be ( )( a) = ba + ca. Let s use the distributive property on a couple of Factoring Review for Algebra II The saddest thing about not doing well in Algebra II is that almost any math teacher can tell you going into it what s going to trip you up. One of the first things they

More information

Notater: INF3331. Veronika Heimsbakk December 4, Introduction 3

Notater: INF3331. Veronika Heimsbakk December 4, Introduction 3 Notater: INF3331 Veronika Heimsbakk veronahe@student.matnat.uio.no December 4, 2013 Contents 1 Introduction 3 2 Bash 3 2.1 Variables.............................. 3 2.2 Loops...............................

More information

Octave. Tutorial. Daniel Lamprecht. March 26, Graz University of Technology. Slides based on previous work by Ingo Holzmann

Octave. Tutorial. Daniel Lamprecht. March 26, Graz University of Technology. Slides based on previous work by Ingo Holzmann Tutorial Graz University of Technology March 26, 2012 Slides based on previous work by Ingo Holzmann Introduction What is? GNU is a high-level interactive language for numerical computations mostly compatible

More information

Designing Information Devices and Systems I Fall 2018 Lecture Notes Note Introduction to Linear Algebra the EECS Way

Designing Information Devices and Systems I Fall 2018 Lecture Notes Note Introduction to Linear Algebra the EECS Way EECS 16A Designing Information Devices and Systems I Fall 018 Lecture Notes Note 1 1.1 Introduction to Linear Algebra the EECS Way In this note, we will teach the basics of linear algebra and relate it

More information

import java. u t i l. ;... Scanner sc = new Scanner ( System. in ) ;

import java. u t i l. ;... Scanner sc = new Scanner ( System. in ) ; CPSC 490 Input Input will always arrive on stdin. You may assume input is well-formed with respect to the problem specification; inappropriate input (e.g. text where a number was specified, number out

More information

Tutorial Three: Loops and Conditionals

Tutorial Three: Loops and Conditionals Tutorial Three: Loops and Conditionals Imad Pasha Chris Agostino February 18, 2015 1 Introduction In lecture Monday we learned that combinations of conditionals and loops could make our code much more

More information

Predictive parsing as a specific subclass of recursive descent parsing complexity comparisons with general parsing

Predictive parsing as a specific subclass of recursive descent parsing complexity comparisons with general parsing Plan for Today Recall Predictive Parsing when it works and when it doesn t necessary to remove left-recursion might have to left-factor Error recovery for predictive parsers Predictive parsing as a specific

More information

5 + 9(10) + 3(100) + 0(1000) + 2(10000) =

5 + 9(10) + 3(100) + 0(1000) + 2(10000) = Chapter 5 Analyzing Algorithms So far we have been proving statements about databases, mathematics and arithmetic, or sequences of numbers. Though these types of statements are common in computer science,

More information

CSCI3390-Assignment 2 Solutions

CSCI3390-Assignment 2 Solutions CSCI3390-Assignment 2 Solutions due February 3, 2016 1 TMs for Deciding Languages Write the specification of a Turing machine recognizing one of the following three languages. Do one of these problems.

More information

Math 31 Lesson Plan. Day 2: Sets; Binary Operations. Elizabeth Gillaspy. September 23, 2011

Math 31 Lesson Plan. Day 2: Sets; Binary Operations. Elizabeth Gillaspy. September 23, 2011 Math 31 Lesson Plan Day 2: Sets; Binary Operations Elizabeth Gillaspy September 23, 2011 Supplies needed: 30 worksheets. Scratch paper? Sign in sheet Goals for myself: Tell them what you re going to tell

More information

COMS 6100 Class Notes

COMS 6100 Class Notes COMS 6100 Class Notes Daniel Solus September 20, 2016 1 General Remarks The Lecture notes submitted by the class have been very good. Integer division seemed to be a common oversight when working the Fortran

More information

Reading and Writing. Mathematical Proofs. Slides by Arthur van Goetham

Reading and Writing. Mathematical Proofs. Slides by Arthur van Goetham Reading and Writing Mathematical Proofs Slides by Arthur van Goetham What is a proof? Why explanations are not proofs What is a proof? A method for establishing truth What establishes truth depends on

More information

CISC 4090: Theory of Computation Chapter 1 Regular Languages. Section 1.1: Finite Automata. What is a computer? Finite automata

CISC 4090: Theory of Computation Chapter 1 Regular Languages. Section 1.1: Finite Automata. What is a computer? Finite automata CISC 4090: Theory of Computation Chapter Regular Languages Xiaolan Zhang, adapted from slides by Prof. Werschulz Section.: Finite Automata Fordham University Department of Computer and Information Sciences

More information

Moving into the information age: From records to Google Earth

Moving into the information age: From records to Google Earth Moving into the information age: From records to Google Earth David R. R. Smith Psychology, School of Life Sciences, University of Hull e-mail: davidsmith.butterflies@gmail.com Introduction Many of us

More information

1 Closest Pair of Points on the Plane

1 Closest Pair of Points on the Plane CS 31: Algorithms (Spring 2019): Lecture 5 Date: 4th April, 2019 Topic: Divide and Conquer 3: Closest Pair of Points on a Plane Disclaimer: These notes have not gone through scrutiny and in all probability

More information

Announcements. Problem Set 6 due next Monday, February 25, at 12:50PM. Midterm graded, will be returned at end of lecture.

Announcements. Problem Set 6 due next Monday, February 25, at 12:50PM. Midterm graded, will be returned at end of lecture. Turing Machines Hello Hello Condensed Slide Slide Readers! Readers! This This lecture lecture is is almost almost entirely entirely animations that that show show how how each each Turing Turing machine

More information

Designing Information Devices and Systems I Spring 2018 Lecture Notes Note Introduction to Linear Algebra the EECS Way

Designing Information Devices and Systems I Spring 2018 Lecture Notes Note Introduction to Linear Algebra the EECS Way EECS 16A Designing Information Devices and Systems I Spring 018 Lecture Notes Note 1 1.1 Introduction to Linear Algebra the EECS Way In this note, we will teach the basics of linear algebra and relate

More information

MiniMat: Matrix Language in OCaml LLVM

MiniMat: Matrix Language in OCaml LLVM Terence Lim - tl2735@columbia.edu August 17, 2016 Contents 1 Introduction 4 1.1 Goals........................................ 4 1.1.1 Flexible matrix notation......................... 4 1.1.2 Uncluttered................................

More information

Math 31 Lesson Plan. Day 5: Intro to Groups. Elizabeth Gillaspy. September 28, 2011

Math 31 Lesson Plan. Day 5: Intro to Groups. Elizabeth Gillaspy. September 28, 2011 Math 31 Lesson Plan Day 5: Intro to Groups Elizabeth Gillaspy September 28, 2011 Supplies needed: Sign in sheet Goals for students: Students will: Improve the clarity of their proof-writing. Gain confidence

More information

Introduction to Python

Introduction to Python Introduction to Python Luis Pedro Coelho Institute for Molecular Medicine (Lisbon) Lisbon Machine Learning School II Luis Pedro Coelho (IMM) Introduction to Python Lisbon Machine Learning School II (1

More information

ECEN 651: Microprogrammed Control of Digital Systems Department of Electrical and Computer Engineering Texas A&M University

ECEN 651: Microprogrammed Control of Digital Systems Department of Electrical and Computer Engineering Texas A&M University ECEN 651: Microprogrammed Control of Digital Systems Department of Electrical and Computer Engineering Texas A&M University Prof. Mi Lu TA: Ehsan Rohani Laboratory Exercise #4 MIPS Assembly and Simulation

More information

Lecture 3. Big-O notation, more recurrences!!

Lecture 3. Big-O notation, more recurrences!! Lecture 3 Big-O notation, more recurrences!! Announcements! HW1 is posted! (Due Friday) See Piazza for a list of HW clarifications First recitation section was this morning, there s another tomorrow (same

More information

Math 3361-Modern Algebra Lecture 08 9/26/ Cardinality

Math 3361-Modern Algebra Lecture 08 9/26/ Cardinality Math 336-Modern Algebra Lecture 08 9/26/4. Cardinality I started talking about cardinality last time, and you did some stuff with it in the Homework, so let s continue. I said that two sets have the same

More information

Turing Machines Part Three

Turing Machines Part Three Turing Machines Part Three What problems can we solve with a computer? What kind of computer? Very Important Terminology Let M be a Turing machine. M accepts a string w if it enters an accept state when

More information

1 ListElement l e = f i r s t ; / / s t a r t i n g p o i n t 2 while ( l e. next!= n u l l ) 3 { l e = l e. next ; / / next step 4 } Removal

1 ListElement l e = f i r s t ; / / s t a r t i n g p o i n t 2 while ( l e. next!= n u l l ) 3 { l e = l e. next ; / / next step 4 } Removal Präsenzstunden Today In the same room as in the first week Assignment 5 Felix Friedrich, Lars Widmer, Fabian Stutz TA lecture, Informatics II D-BAUG March 18, 2014 HIL E 15.2 15:00-18:00 Timon Gehr (arriving

More information

Lectures about Python, useful both for beginners and experts, can be found at (http://scipy-lectures.github.io).

Lectures about Python, useful both for beginners and experts, can be found at  (http://scipy-lectures.github.io). Random Matrix Theory (Sethna, "Entropy, Order Parameters, and Complexity", ex. 1.6, developed with Piet Brouwer) 2016, James Sethna, all rights reserved. This is an ipython notebook. This hints file is

More information

Chapter 2. Mathematical Reasoning. 2.1 Mathematical Models

Chapter 2. Mathematical Reasoning. 2.1 Mathematical Models Contents Mathematical Reasoning 3.1 Mathematical Models........................... 3. Mathematical Proof............................ 4..1 Structure of Proofs........................ 4.. Direct Method..........................

More information

Week 2: Defining Computation

Week 2: Defining Computation Computational Complexity Theory Summer HSSP 2018 Week 2: Defining Computation Dylan Hendrickson MIT Educational Studies Program 2.1 Turing Machines Turing machines provide a simple, clearly defined way

More information

Computer Science 324 Computer Architecture Mount Holyoke College Fall Topic Notes: Digital Logic

Computer Science 324 Computer Architecture Mount Holyoke College Fall Topic Notes: Digital Logic Computer Science 324 Computer Architecture Mount Holyoke College Fall 2007 Topic Notes: Digital Logic Our goal for the next few weeks is to paint a a reasonably complete picture of how we can go from transistor

More information

Lisp Introduction. Dr. Neil T. Dantam. Spring CSCI-498/598 RPM, Colorado School of Mines. Dantam (Mines CSCI, RPM) Lisp Spring / 88

Lisp Introduction. Dr. Neil T. Dantam. Spring CSCI-498/598 RPM, Colorado School of Mines. Dantam (Mines CSCI, RPM) Lisp Spring / 88 Lisp Introduction Dr. Neil T. Dantam CSCI-498/598 RPM, Colorado School of Mines Spring 28 Dantam (Mines CSCI, RPM) Lisp Spring 28 / 88 Outline Lisp Common Lisp by Example Implementation Details Typing

More information

Hypothesis testing I. - In particular, we are talking about statistical hypotheses. [get everyone s finger length!] n =

Hypothesis testing I. - In particular, we are talking about statistical hypotheses. [get everyone s finger length!] n = Hypothesis testing I I. What is hypothesis testing? [Note we re temporarily bouncing around in the book a lot! Things will settle down again in a week or so] - Exactly what it says. We develop a hypothesis,

More information

Comp 11 Lectures. Mike Shah. July 12, Tufts University. Mike Shah (Tufts University) Comp 11 Lectures July 12, / 33

Comp 11 Lectures. Mike Shah. July 12, Tufts University. Mike Shah (Tufts University) Comp 11 Lectures July 12, / 33 Comp 11 Lectures Mike Shah Tufts University July 12, 2017 Mike Shah (Tufts University) Comp 11 Lectures July 12, 2017 1 / 33 Please do not distribute or host these slides without prior permission. Mike

More information

CSE 331 Winter 2018 Homework 1

CSE 331 Winter 2018 Homework 1 Directions: - Due Wednesday, January 10 by 11 pm. - Turn in your work online using gradescope. You should turn in a single pdf file. You can have more than one answer per page, but please try to avoid

More information

(a) Definition of TMs. First Problem of URMs

(a) Definition of TMs. First Problem of URMs Sec. 4: Turing Machines First Problem of URMs (a) Definition of the Turing Machine. (b) URM computable functions are Turing computable. (c) Undecidability of the Turing Halting Problem That incrementing

More information

CS 124 Math Review Section January 29, 2018

CS 124 Math Review Section January 29, 2018 CS 124 Math Review Section CS 124 is more math intensive than most of the introductory courses in the department. You re going to need to be able to do two things: 1. Perform some clever calculations to

More information

MITOCW ocw-18_02-f07-lec02_220k

MITOCW ocw-18_02-f07-lec02_220k MITOCW ocw-18_02-f07-lec02_220k The following content is provided under a Creative Commons license. Your support will help MIT OpenCourseWare continue to offer high quality educational resources for free.

More information

Please bring the task to your first physics lesson and hand it to the teacher.

Please bring the task to your first physics lesson and hand it to the teacher. Pre-enrolment task for 2014 entry Physics Why do I need to complete a pre-enrolment task? This bridging pack serves a number of purposes. It gives you practice in some of the important skills you will

More information

What Every Programmer Should Know About Floating-Point Arithmetic DRAFT. Last updated: November 3, Abstract

What Every Programmer Should Know About Floating-Point Arithmetic DRAFT. Last updated: November 3, Abstract What Every Programmer Should Know About Floating-Point Arithmetic Last updated: November 3, 2014 Abstract The article provides simple answers to the common recurring questions of novice programmers about

More information

Getting Started with Communications Engineering

Getting Started with Communications Engineering 1 Linear algebra is the algebra of linear equations: the term linear being used in the same sense as in linear functions, such as: which is the equation of a straight line. y ax c (0.1) Of course, if we

More information

One-to-one functions and onto functions

One-to-one functions and onto functions MA 3362 Lecture 7 - One-to-one and Onto Wednesday, October 22, 2008. Objectives: Formalize definitions of one-to-one and onto One-to-one functions and onto functions At the level of set theory, there are

More information

Algebra Exam. Solutions and Grading Guide

Algebra Exam. Solutions and Grading Guide Algebra Exam Solutions and Grading Guide You should use this grading guide to carefully grade your own exam, trying to be as objective as possible about what score the TAs would give your responses. Full

More information

Example: 2x y + 3z = 1 5y 6z = 0 x + 4z = 7. Definition: Elementary Row Operations. Example: Type I swap rows 1 and 3

Example: 2x y + 3z = 1 5y 6z = 0 x + 4z = 7. Definition: Elementary Row Operations. Example: Type I swap rows 1 and 3 Linear Algebra Row Reduced Echelon Form Techniques for solving systems of linear equations lie at the heart of linear algebra. In high school we learn to solve systems with or variables using elimination

More information

Cosets and Lagrange s theorem

Cosets and Lagrange s theorem Cosets and Lagrange s theorem These are notes on cosets and Lagrange s theorem some of which may already have been lecturer. There are some questions for you included in the text. You should write the

More information

An analogy from Calculus: limits

An analogy from Calculus: limits COMP 250 Fall 2018 35 - big O Nov. 30, 2018 We have seen several algorithms in the course, and we have loosely characterized their runtimes in terms of the size n of the input. We say that the algorithm

More information

Binary addition example worked out

Binary addition example worked out Binary addition example worked out Some terms are given here Exercise: what are these numbers equivalent to in decimal? The initial carry in is implicitly 0 1 1 1 0 (Carries) 1 0 1 1 (Augend) + 1 1 1 0

More information

Chapter 1. Foundations of GMAT Math. Arithmetic

Chapter 1. Foundations of GMAT Math. Arithmetic Chapter of Foundations of GMAT Math In This Chapter Quick-Start Definitions Basic Numbers Greater Than and Less Than Adding and Subtracting Positives and Negatives Multiplying and Dividing Distributing

More information

CE 365K Exercise 1: GIS Basemap for Design Project Spring 2014 Hydraulic Engineering Design

CE 365K Exercise 1: GIS Basemap for Design Project Spring 2014 Hydraulic Engineering Design CE 365K Exercise 1: GIS Basemap for Design Project Spring 2014 Hydraulic Engineering Design The purpose of this exercise is for you to construct a basemap in ArcGIS for your design project. You may execute

More information

: Intro Programming for Scientists and Engineers Assignment 4: Learning from Echocardiograms

: Intro Programming for Scientists and Engineers Assignment 4: Learning from Echocardiograms Assignment 4: Learning from Echocardiograms Page 1 600.112: Intro Programming for Scientists and Engineers Assignment 4: Learning from Echocardiograms Peter H. Fröhlich phf@cs.jhu.edu Joanne Selinski joanne@cs.jhu.edu

More information

2 Systems of Linear Equations

2 Systems of Linear Equations 2 Systems of Linear Equations A system of equations of the form or is called a system of linear equations. x + 2y = 7 2x y = 4 5p 6q + r = 4 2p + 3q 5r = 7 6p q + 4r = 2 Definition. An equation involving

More information

Error Correcting Codes Prof. Dr. P. Vijay Kumar Department of Electrical Communication Engineering Indian Institute of Science, Bangalore

Error Correcting Codes Prof. Dr. P. Vijay Kumar Department of Electrical Communication Engineering Indian Institute of Science, Bangalore (Refer Slide Time: 00:15) Error Correcting Codes Prof. Dr. P. Vijay Kumar Department of Electrical Communication Engineering Indian Institute of Science, Bangalore Lecture No. # 03 Mathematical Preliminaries:

More information

Hoare Logic: Reasoning About Imperative Programs

Hoare Logic: Reasoning About Imperative Programs Hoare Logic: Reasoning About Imperative Programs COMP1600 / COMP6260 Dirk Pattinson Australian National University Semester 2, 2018 Programming Paradigms Functional. (Haskell, SML, OCaml,... ) main paradigm:

More information

CSE 331 Winter 2018 Reasoning About Code I

CSE 331 Winter 2018 Reasoning About Code I CSE 331 Winter 2018 Reasoning About Code I Notes by Krysta Yousoufian Original lectures by Hal Perkins Additional contributions from Michael Ernst, David Notkin, and Dan Grossman These notes cover most

More information

Unit 8: Sequ. ential Circuits

Unit 8: Sequ. ential Circuits CPSC 121: Models of Computation Unit 8: Sequ ential Circuits Based on slides by Patrice Be lleville and Steve Wolfman Pre-Class Learning Goals By the start of class, you s hould be able to Trace the operation

More information

Ratios, Proportions, Unit Conversions, and the Factor-Label Method

Ratios, Proportions, Unit Conversions, and the Factor-Label Method Ratios, Proportions, Unit Conversions, and the Factor-Label Method Math 0, Littlefield I don t know why, but presentations about ratios and proportions are often confused and fragmented. The one in your

More information

C if U can. Algebra. Name

C if U can. Algebra. Name C if U can Algebra Name.. How will this booklet help you to move from a D to a C grade? The topic of algebra is split into six units substitution, expressions, factorising, equations, trial and improvement

More information

Using Microsoft Excel

Using Microsoft Excel Using Microsoft Excel Objective: Students will gain familiarity with using Excel to record data, display data properly, use built-in formulae to do calculations, and plot and fit data with linear functions.

More information

Anatomy of SINGULAR talk at p. 1

Anatomy of SINGULAR talk at p. 1 Anatomy of SINGULAR talk at MaGiX@LIX 2011- p. 1 Anatomy of SINGULAR talk at MaGiX@LIX 2011 - Hans Schönemann hannes@mathematik.uni-kl.de Department of Mathematics University of Kaiserslautern Anatomy

More information

Turing Machines Part II

Turing Machines Part II Turing Machines Part II Problem Set Set Five Five due due in in the the box box up up front front using using a late late day. day. Hello Hello Condensed Slide Slide Readers! Readers! This This lecture

More information

1 Maintaining a Dictionary

1 Maintaining a Dictionary 15-451/651: Design & Analysis of Algorithms February 1, 2016 Lecture #7: Hashing last changed: January 29, 2016 Hashing is a great practical tool, with an interesting and subtle theory too. In addition

More information

R: A Quick Reference

R: A Quick Reference R: A Quick Reference Colorado Reed January 17, 2012 Contents 1 Basics 2 1.1 Arrays and Matrices....................... 2 1.2 Lists................................ 3 1.3 Loading Packages.........................

More information

And, even if it is square, we may not be able to use EROs to get to the identity matrix. Consider

And, even if it is square, we may not be able to use EROs to get to the identity matrix. Consider .2. Echelon Form and Reduced Row Echelon Form In this section, we address what we are trying to achieve by doing EROs. We are trying to turn any linear system into a simpler one. But what does simpler

More information

CS173 Lecture B, November 3, 2015

CS173 Lecture B, November 3, 2015 CS173 Lecture B, November 3, 2015 Tandy Warnow November 3, 2015 CS 173, Lecture B November 3, 2015 Tandy Warnow Announcements Examlet 7 is a take-home exam, and is due November 10, 11:05 AM, in class.

More information

One sided tests. An example of a two sided alternative is what we ve been using for our two sample tests:

One sided tests. An example of a two sided alternative is what we ve been using for our two sample tests: One sided tests So far all of our tests have been two sided. While this may be a bit easier to understand, this is often not the best way to do a hypothesis test. One simple thing that we can do to get

More information

Math101, Sections 2 and 3, Spring 2008 Review Sheet for Exam #2:

Math101, Sections 2 and 3, Spring 2008 Review Sheet for Exam #2: Math101, Sections 2 and 3, Spring 2008 Review Sheet for Exam #2: 03 17 08 3 All about lines 3.1 The Rectangular Coordinate System Know how to plot points in the rectangular coordinate system. Know the

More information

Satellite project, AST 1100

Satellite project, AST 1100 Satellite project, AST 1100 Introduction and useful information 0.1 Project overview In this project you are going to send a satellite from your home planet, in your own personal star system, to visit

More information

Lecture 27: Theory of Computation. Marvin Zhang 08/08/2016

Lecture 27: Theory of Computation. Marvin Zhang 08/08/2016 Lecture 27: Theory of Computation Marvin Zhang 08/08/2016 Announcements Roadmap Introduction Functions Data Mutability Objects This week (Applications), the goals are: To go beyond CS 61A and see examples

More information

Experiment 1: The Same or Not The Same?

Experiment 1: The Same or Not The Same? Experiment 1: The Same or Not The Same? Learning Goals After you finish this lab, you will be able to: 1. Use Logger Pro to collect data and calculate statistics (mean and standard deviation). 2. Explain

More information

Turing Machine Recap

Turing Machine Recap Turing Machine Recap DFA with (infinite) tape. One move: read, write, move, change state. High-level Points Church-Turing thesis: TMs are the most general computing devices. So far no counter example Every

More information

CS1800: Mathematical Induction. Professor Kevin Gold

CS1800: Mathematical Induction. Professor Kevin Gold CS1800: Mathematical Induction Professor Kevin Gold Induction: Used to Prove Patterns Just Keep Going For an algorithm, we may want to prove that it just keeps working, no matter how big the input size

More information

Ch. 3 Equations and Inequalities

Ch. 3 Equations and Inequalities Ch. 3 Equations and Inequalities 3.1 Solving Linear Equations Graphically There are 2 methods presented in this section for solving linear equations graphically. Normally I would not cover solving linear

More information

CHAPTER 7: TECHNIQUES OF INTEGRATION

CHAPTER 7: TECHNIQUES OF INTEGRATION CHAPTER 7: TECHNIQUES OF INTEGRATION DAVID GLICKENSTEIN. Introduction This semester we will be looking deep into the recesses of calculus. Some of the main topics will be: Integration: we will learn how

More information

Course Announcements. John Jannotti (cs32) Scope, Collections & Generics Feb 8, / 1

Course Announcements. John Jannotti (cs32) Scope, Collections & Generics Feb 8, / 1 Course Announcements Stars is due tomorrow. Stars grades should be out by next Monday. Javascript lab out today. How you make interactive webby GUIs. Today we re going to cover a bit of a hodge podge.

More information

Confidence intervals

Confidence intervals Confidence intervals We now want to take what we ve learned about sampling distributions and standard errors and construct confidence intervals. What are confidence intervals? Simply an interval for which

More information

Blocking Synchronization: Streams Vijay Saraswat (Dec 10, 2012)

Blocking Synchronization: Streams Vijay Saraswat (Dec 10, 2012) 1 Streams Blocking Synchronization: Streams Vijay Saraswat (Dec 10, 2012) Streams provide a very simple abstraction for determinate parallel computation. The intuition for streams is already present in

More information

Scripting Languages Fast development, extensible programs

Scripting Languages Fast development, extensible programs Scripting Languages Fast development, extensible programs Devert Alexandre School of Software Engineering of USTC November 30, 2012 Slide 1/60 Table of Contents 1 Introduction 2 Dynamic languages A Python

More information

Math 308 Midterm Answers and Comments July 18, Part A. Short answer questions

Math 308 Midterm Answers and Comments July 18, Part A. Short answer questions Math 308 Midterm Answers and Comments July 18, 2011 Part A. Short answer questions (1) Compute the determinant of the matrix a 3 3 1 1 2. 1 a 3 The determinant is 2a 2 12. Comments: Everyone seemed to

More information

MA554 Assessment 1 Cosets and Lagrange s theorem

MA554 Assessment 1 Cosets and Lagrange s theorem MA554 Assessment 1 Cosets and Lagrange s theorem These are notes on cosets and Lagrange s theorem; they go over some material from the lectures again, and they have some new material it is all examinable,

More information

Final Review Sheet. B = (1, 1 + 3x, 1 + x 2 ) then 2 + 3x + 6x 2

Final Review Sheet. B = (1, 1 + 3x, 1 + x 2 ) then 2 + 3x + 6x 2 Final Review Sheet The final will cover Sections Chapters 1,2,3 and 4, as well as sections 5.1-5.4, 6.1-6.2 and 7.1-7.3 from chapters 5,6 and 7. This is essentially all material covered this term. Watch

More information

An Introduction to Z3

An Introduction to Z3 An Introduction to Z3 Huixing Fang National Trusted Embedded Software Engineering Technology Research Center April 12, 2017 Outline 1 SMT 2 Z3 Huixing Fang (ECNU) An Introduction to Z3 April 12, 2017 2

More information

1 Definition of a Turing machine

1 Definition of a Turing machine Introduction to Algorithms Notes on Turing Machines CS 4820, Spring 2017 April 10 24, 2017 1 Definition of a Turing machine Turing machines are an abstract model of computation. They provide a precise,

More information

SUPPLEMENTARY INFORMATION

SUPPLEMENTARY INFORMATION SUPPLEMENTARY INFORMATION doi:10.1038/nature11875 Method for Encoding and Decoding Arbitrary Computer Files in DNA Fragments 1 Encoding 1.1: An arbitrary computer file is represented as a string S 0 of

More information

CMSC 451: Lecture 7 Greedy Algorithms for Scheduling Tuesday, Sep 19, 2017

CMSC 451: Lecture 7 Greedy Algorithms for Scheduling Tuesday, Sep 19, 2017 CMSC CMSC : Lecture Greedy Algorithms for Scheduling Tuesday, Sep 9, 0 Reading: Sects.. and. of KT. (Not covered in DPV.) Interval Scheduling: We continue our discussion of greedy algorithms with a number

More information