CS代考 CSI2120/demoCode.html

Programming Paradigms

• Course overview •Introduction to programming
• Review: The object-oriented

Copyright By PowCoder代写 加微信 powcoder

paradigm in Java
•Imperative and concurrent programming paradigm: Go.
• Logic paradigm: Prolog.
• Functional paradigm: Scheme.

Announcement
•Office hours for comprehensive assignment(assignment 1)
• 5|moreofficehours
• check brightSpace for information • Thursday Jan TBA on BS – Live
Q&A: Assignment and Go
• Recorded labs and Tutorial posted

Acknowledgment
The slides posted through the term are based of the slides offered by:
Prof. Jochen Lang
Demo code: https://www.site.uottawa.ca/~jl ang/CSI2120/demoCode.html

System Programming: Go
Stream I/O
Panic and Recover Methods Interfaces Embedded Types
Console I/O File I/O

Console I/O
• ConsoleI/Owithpackagefmt.C-likesyntaxwithscanf and printf in addition to print (println).
package main import “fmt”
func main() {
var inStr string fmt.Printf(“Input? “) fmt.Scanf(“%s”, &inStr) fmt.Printf(“\nOutput: %s\n”, inStr)

• File I/O follows familiar notion of stream I/O
• Relevant packages are os and bufio besides fmt
func fCopy(outN, inN string) (bytesOut int64, err
inF, err := os.Open(inN)
if err != nil {
} return
outF, err := os.Create(outN)
if err != nil {
inF.Close()
} return
bytesOut, err = io.Copy(outF, inF)
inF.Close(); outF.Close()

Final Evaluation with defer
• Withdefertheexecutionofastatementcanbedeferred to the end of a function or block.
• Convenientforcleaningupattheendofmultiplecontrol path through a function.
– E.g., file handles
• Theparametersofadelayedfunctionareevaluatedatthe issue of the defer statement.
• Theexecutionofadeferredfunctiontakesplaceevenif the function is exited with an error

File Copy with Deferred Clean-up
• Defer simplifies error handling
func fCopy(outN, inN string) (bytesOut int64, err
inF, err := os.Open(inN)
if err != nil {
} return
defer inF.Close()
outF, err := os.Create(outN)
if err != nil {
} return
defer outF.Close()
bytesOut, err = io.Copy(outF, inF)

Errors and Panic in Go
• No exceptions in Go
• Instead of exception return error codes of type error
– Convention: On success error is nil
• When a serious error occurs, use the panic statement
– Only to be used for unforeseen errors
– Corresponds to violations of assertions (C assert
statement)
• In case of panic:
– function stops immediately
– deferred functions are executed – stack unwinding occurs
• return to the calling functions
• executing their deferred functions until main exits • can be stopped with recover

Panic Toy Example
package main import “fmt” func main() {
defer fmt.Println(“Last Output”)
fmt.Println(“Before Panic” )
panic(“Out of here”)
fmt.Println(“After Panic”)
Before Panic
Last Output
panic: Out of here
goroutine 1 [running]:
runtime.panic(0x48d4e0, 0xc084005260) C:/Users/ADMINI~1/AppData/Local/Temp/2/makerelease2
50988475/go/src/pkg/runtime/panic.c:266 +0xc8 main.main()
c:/teaching/CSI2120/demoCode/go/panictoy.go:8 +0x18e

Panic and Recover
package main
import “fmt”
func causePanic() {
} panic(“Caused panic”)
func foo() {
defer func() {
if err := recover(); err != nil {
fmt.Printf(“Recovered from >> %s <<\n", err) } causePanic() } fmt.Println("Regularafterpanic") //notshown func main() { fmt.Println("In main:") fmt.Println("End main:") } Example Run Recover and Go • Programterminatesregularly • Notethatfunctionfooisexitedthroughadeferred function call Recovered from >> Caused panic << Recover after panic • The statement recovers to regain control after a panic • To be used in a deferred function • In the absence of panic, the recover simply returns nil Methods and Receivers • Amethodisafunctionactsonacertaintype(itsreceiver)ora structure • Receivertypecanbeapointertoanallowedtype. – mandatory if the method changes the attributes of the case • Thestructureandmethodsarenotgroupedtogether – they only have to be in the same package (but can be in different source files) – no encapsulation as with classes • Nomethodoverloading(justaswithfunctions) Definition of and Calling a Method package main "fmt" ) "math" type Point struct { x.float64 } y.float64 func (pt *Point) norm() float64 { } return math.Sqrt(pt.x*pt.x + pt.y*pt.y) func main() { a := Point{2.,4.} n := a.norm() fmt.Printf("2-Norm = %f\n", n) Interfaces • Interfacesdefineasetofmethods – no code for the method – abstract definitions • Namingconvention – Interface name should end in “er”, e.g., Writer, Reader, Logger etc. • Implementinganinterface – A type does not need to state that implements an interface – A type can implement multiple interfaces – Interface can embed other interfaces – Interfaces can be assigned to variables Interface example type ColorPt struct { } color string type Box struct { weight float64 } color string // interface to be implemented by ColorPt and Box type Color interface { SetColor(string) Color() string Implementation of an Interface • Interface implementation for type ColorPt func (p *ColorPt) Color() string { } returnp.color func (p *ColorPt) SetColor(col string) { p.color = col } • Interface implementation for type Box func (p *Box) SetColor(col string) { } p.color=col func (p *Box) Color() string { return p.color Polymorphism with Interfaces • Use an array of pointers to structures implementing the Color interface func main() { table := [...]Color{ &ColorPt{Point{1.1,2.2},"red"}, &Box{32.4, "yellow"}, &ColorPt{Point{3.1,1.2},"blue"}} for _,element := range table { fmt.Printf("color= %s\n", element.Color()) Binary tree type Tree struct { Left *Tree Right *Tree } func NewTree(v int) *Tree { return &Tree{nil, v, nil} } func (t *Tree) InOrder() { if t.Left != nil { } t.Left.InOrder() fmt.Println(t.Value) if t.Right != nil { } t.Right.InOrder() Insertion in binary search tree type Tree struct { Left *Tree Value int Right *Tree func NewTree(v int) *Tree { return &Tree{nil, v, nil} func (t *Tree) InOrder() { func main() { t:= NewTree(5) t.Insert(7) t.Insert(9) t.Insert(2) } t.InOrder() if t.Left != nil { } t.Left.InOrder() fmt.Println(t.Value) if t.Right != nil { } t.Right.InOrder() A generic Go queue Tip: Use the empty interface that is satisfied by all GO types • However, this solution is not type Queue struct { } items []interface{} very efficient // Enqueue adds a value to the // end of the queue func (s *Queue) Enqueue(t interface{}) { s.items = append(s.items, t) // Dequeue removes a value from the // start of the queue func (s *Queue) Dequeue() interface{} { item := s.items[0] s.items = s.items[1:len(s.items)] return item A generic Go queue // Front returns the item next in // the queue, without removing it func (s *Queue) Front() *interface{} { item := s.items[0] } return &item func main() { var queue Queue queue.Enqueue(10) queue.Enqueue(20) queue.Enqueue(30) // IsEmpty returns true if the // queue is empty func (s *Queue) IsEmpty() bool { return len(s.items) == 0 t:= queue.Dequeue() fmt.Println("value=",t) queue.Enqueue(40) // Size returns the number of elements func (s *Queue) Size() int { return len(s.items) queue.Enqueue(50) queue.Enqueue(60) t= queue.Dequeue() t= queue.Dequeue() t= queue.Dequeue() fmt.Println("value(2)=",t) fmt.Println("size=",queue.Size()) fmt.Println("front=",*queue.Front()) • StreamI/O – Console I/O – File I/O • PanicandRecover • Methods • Interfaces • Embeddedtypes 程序代写 CS代考 加微信: powcoder QQ: 1823890830 Email: powcoder@163.com