Golang Functions Functions allow modularization func MySqrt(f float64) (v float64, ok bool) { if f >= 0 { v,ok = math.Sqrt(f), true } return v, ok //or.

Slides:



Advertisements
Similar presentations
Introduction to C Programming
Advertisements

Programming Languages and Paradigms The C Programming Language.
Programming Paradigms Introduction. 6/15/2005 Copyright 2005, by the authors of these slides, and Ateneo de Manila University. All rights reserved. L1:
Abstract Data Types Data abstraction, or abstract data types, is a programming methodology where one defines not only the data structure to be used, but.
6/10/2015C++ for Java Programmers1 Pointers and References Timothy Budd.
George Blank University Lecturer. CS 602 Java and the Web Object Oriented Software Development Using Java Chapter 4.
Road Map Introduction to object oriented programming. Classes
Cse321, Programming Languages and Compilers 1 6/12/2015 Lecture #17, March 12, 2007 Procedure Abstraction, Name Spaces, Scoping Rules, Activation Records,
Unit 181 Recursion Definition Recursive Methods Example 1 How does Recursion work? Example 2 Problems with Recursion Infinite Recursion Exercises.
1 Introduction to Recursion  Introduction to Recursion  Example 1: Factorial  Example 2: Reversing Strings  Example 3: Fibonacci  Infinite Recursion.
Names and Scopes CS 351. Program Binding We should be familiar with this notion. A variable is bound to a method or current block e.g in C++: namespace.
© Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. Chapter 5 - Functions Outline 5.1Introduction 5.2Program.
Recursion CS-240/CS341. What is recursion? a function calls itself –direct recursion a function calls its invoker –indirect recursion f f1 f2.
Terms and Rules Professor Evan Korth New York University (All rights reserved)
1 Run time vs. Compile time The compiler must generate code to handle issues that arise at run time Representation of various data types Procedure linkage.
Copyright © 2006 The McGraw-Hill Companies, Inc. Programming Languages 2nd edition Tucker and Noonan Chapter 5 Types Types are the leaven of computer programming;
Java Methods By J. W. Rider. Java Methods Modularity Declaring methods –Header, signature, prototype Static Void Local variables –this Return Reentrancy.
Types(2). 2 Recursive Problems  One or more simple cases of the problem have a straightforward, nonrecusive solution  The other cases can be redefined.
Stacks & Recursion. Stack pushpop LIFO list - only top element is visible top.
Scott Marino MSMIS Kean University MSAS5104 Programming with Data Structures and Algorithms Week 10 Scott Marino.
1 TCSS 143, Autumn 2004 Lecture Notes Recursion Koffman/Wolfgang Ch. 7, pp ,
Arrays Module 6. Objectives Nature and purpose of an array Using arrays in Java programs Methods with array parameter Methods that return an array Array.
Basic Semantics Associating meaning with language entities.
Session 08 Module 14: Generics and Iterator Module 15: Anonymous & partial class & Nullable type.
Functional Programming With examples in F#. Pure Functional Programming Functional programming involves evaluating expressions rather than executing commands.
With Python.  One of the most useful abilities of programming is the ability to manipulate files.  Python’s operations for file management are relatively.
Basic Java Syntax COMP 401, Spring 2014 Lecture 2 1/14/2014.
Chapter 14 Abstract Classes and Interfaces. Abstract Classes An abstract class extracts common features and functionality of a family of objects An abstract.
Python Primer 1: Types and Operators © 2013 Goodrich, Tamassia, Goldwasser1Python Primer.
Lecture 2 Functions. Functions in C++ long factorial(int n) The return type is long. That means the function will return a long integer to the calling.
Arrays Chapter 7. MIS Object Oriented Systems Arrays UTD, SOM 2 Objectives Nature and purpose of an array Using arrays in Java programs Methods.
UMass Lowell Computer Science Java and Distributed Computing Prof. Karen Daniels Fall, 2000 Lecture 10 Java Fundamentals Objects/ClassesMethods.
FASTFAST All rights reserved © MEP Make programming fun again.
Golang Control Statements if if x < 0 { … } else { … } if v,err:=eval(me);v > 0 && err != nil { … }
Arrays Chapter 7.
CS314 – Section 5 Recitation 9
History of Computing – Golang
CS 215 Final Review Ismail abumuhfouz Fall 2014.
Arrays An array is a grouping of elements of the same type that share a common base name Can have any number of elements in the array Individual elements.
Learn Go Fast With Riley.
Exceptions, Interfaces & Generics
Why exception handling in C++?
Programming for Mobile Technologies
CS 2304 Function Pointers & Lambda Functions
I/O Basics.
Using local variable without initialization is an error.
Formatted and Unformatted Input/Output Functions
Chapter 5 - Functions Outline 5.1 Introduction
Recursion "To understand recursion, one must first understand recursion." -Stephen Hawking.
Applied Algorithms (Lecture 17) Recursion Fall-23
Pointers, Dynamic Data, and Reference Types
The Building Blocks Classes: Java class library, over 1,800 classes:
Generics.
Classes and Objects.
Search,Sort,Recursion.
Unit 3 Test: Friday.
Python Primer 1: Types and Operators
CS302 - Data Structures using C++
Activation records Programming Language Design and Implementation (4th Edition) by T. Pratt and M. Zelkowitz Prentice Hall, 2001 Section
Arrays An array is a grouping of elements of the same type that share a common base name Can have any number of elements in the array Individual elements.
Chapter 18 Recursion.
Handout-16 Recursion Overview
Just Enough Java 17-May-19.
各題答對人數.
More Scheme CS 331.
Activation records Programming Language Design and Implementation (4th Edition) by T. Pratt and M. Zelkowitz Prentice Hall, 2001 Section
Arrays.
Lecture 20 – Practice Exercises 4
Chapter 7 Objects and Classes
Chapter 5 Classes.
Presentation transcript:

Golang Functions Functions allow modularization func MySqrt(f float64) (v float64, ok bool) { if f >= 0 { v,ok = math.Sqrt(f), true } return v, ok //or simply return } value, ok := MySqrt(50.0) or Value, _ := MySqrt(50.0)

Golang Functions Functions cannot access variable in the calling function func f() { fmt.Println(x) } func main() { x := 5 f() } Either declare a global ‘x’ or pass it to the function f(x)

Golang Function are executed on stack func f2() { fmt.Println("in f2") } func f1() { fmt.Println("in f1") f2() } func main() { b() }

Golang Functions can return multiple values package main func sqrt(x float64) (float64,error) { … } func main() { var x float64 = 5.76 square_root, err := sqrt(x) if err == nil { …. }

Golang defer statement : runs before the function returns, helps cleanup package main import "fmt” func trace(s string) { fmt.Println("entering:", s) } func untrace(s string) { fmt.Println("leaving:", s) } func a() { trace("a") defer untrace("a") fmt.Println("in a") } func b() { trace("b") defer untrace("b") fmt.Println("in b") a() } func main() { b() }

Golang Function Literals are Closure Create a func inside a function It has access to the local variables in that scope func main() { x := 0 f := func() int { x += 2 } fmt.Println(f()) }

Golang Function Literals are Closure func adder() func(int) int { var x int return func(delta int) int { x += delta return x } func main() { f := adder() fmt.Println(f(1)) fmt.Println(f(20)) fmt.Println(f(300)) }

Golang No inner functions Pass by value vs reference Variadic Functions func add(args...int) int => add(1,3,5,7)

Golang By using... before the type name of the last parameter you can indicate that it takes zero or more of those parameters. func add(args...int) int { total := 0 for _, v := range args { total += v } return total } func main() { fmt.Println(add(1,2,3)) }

Golang Recursion Recursion happen when a function calls itself Closure and Recursion are two power prnciples of functional programming. func factorial(x uint) uint { if x == 0 { return 1 } return x * factorial(x-1) } factorial(3) => 3 * factorial(2) => 3 * 2 * factorial(1) => 3 * 2 * 1 * factorial(0) => 3 * 2 * 1 * 1

Golang Panic and Recover panic is a built-in function which causes a run time error panic() stops the execution of the function and returns (unwinds the stack) It unwinds the stack until a recover() function handles the panic func main() { panic("PANIC") str := recover() fmt.Println(str) }

Golang Pass by Value vs Reference func square_values(x float64) { return x * x } func square(x *float64) { *x = *x * *x } func main() { x := 1.5 square(&x) }

Golang Exercise Write a function which takes an integer and halves it and returns true if it was even or false if it was odd. For example half(1) should return (0, false) and half(2) should return (1, true) Write a function with one variadic parameter that finds the greatest number in a list of numbers. Homework The Fibonacci sequence is defined as: fib(0) = 0, fib(1) = 1, fib(n) = fib(n-1) + fib(n-2). Write a recursive function which can find fib(n)

Golang Methods on Structures type point struct { x, y float64 } // A method on Point, passing point p in value func (p point) Dist(point p1) float64 { return math.Sqrt(math.Sqr(p.x-p1.x) + math.Sqr(p.y-p1.y)) } or better func (p *Point3) Dist(point p1) float64 { return math.Sqrt(math.Pow(p.x-p1.x,2) + math.Pow(p.y-p1.y,2)) } p,p1 := point{0,0}, point{3,4} p.Dist(p1) //should return 5

Golang Methods on Anonymous Structures Anonymous embedding allows to call methods directly on that struct. type point struct { x, y float64 } func (p *Point3) Dist(point p1) float64 { return math.Sqrt(math.Pow(p.x-p1.x,2) + math.Pow(p.y-p1.y,2)) } type circle struct { point radius float64 } circle c1 = circle{point{0,0},4}, c2 = circle{point{2,3},4} Distance between circles => c1.dist(c2.point)

Golang Methods are attached to a named type, say Foo and are statically bound Go automatically indirects/dereferences values for you when invoking methods. Methods are not just for structs. They can be defined for any (non- pointer) type. type Day int func (day Day) String() string { … }

Golang Scoping 1)Go has package scope (C++ has file scope). 2) Spelling determines exported/local (pub/priv). 3) Structs in the same package have full access to one another's fields and methods. 4) Local type can export its fields and methods. 5) No true subclassing, so no notion of "protected".

Golang Scoping 1)Go has package scope (C++ has file scope). 2) Spelling determines exported/local (pub/priv). 3) Structs in the same package have full access to one another's fields and methods. 4) Local type can export its fields and methods. 5) No true subclassing, so no notion of "protected".

Golang Interfaces Interfaces define sets of methods. They are pure and abstract: no implementation, no data fields. Go has a clear separation between interface and implementation. Interface values are just that: values. They contain any concrete value that implements all the methods defined in the interface. Types implement interfaces just by having methods. They do not have to declare that they do so. For instance, every type implements the empty interface, interface{}.

Golang Sort Interface Has three methods type Interface interface { // Len is the number of elements in the collection. Len() intint // Less reports whether the element with // index i should sort before the element with index j. Less(i, j int) boolint) bool // Swap swaps the elements with indexes i and j. Swap(i, j int)int) }

Golang Sort Interface Exercise : Write a function that sorts the table container player, points scored in the alphabetical order Homework : Create a employee structure with name, age and salary. Implement sort interface on the employee display employee records alphabetically by name or numerically in ascending order on salary.