f# for python programmers. goals goals motivation mapping key features python -> f# angles to tackle...

69
F# for python programmers

Upload: paul-gregory

Post on 06-Jan-2018

243 views

Category:

Documents


0 download

DESCRIPTION

Python Python interpreter yourcode.pyc Python byte code.pyc source1.py source2.py source3.py python.exe compiler/interpreter Python.exe Python.py libs Python, 3 rd party C libs (.so,.dll)

TRANSCRIPT

F# for python programmersAngles to tackle
Architecture and Terminology
source1.fs
source2.fs
source3.fs
F# Applications at Amyris
History
Readable, High level language, built in data structures, sensible error handling, relatively terse
Only things I ever craved were..
More speed…
Better built in numeric support e.g arrays, matrices
What aspects of a language make a Programmer Productive?
High level data structures built in
dicts, lists, tuples, syntax to support them
Terse (typing is expensive)
Easy to use encapsulation mechanisms
Operators
3/4/2011 8:14 PM
© 2007 Microsoft Corporation. All rights reserved. Microsoft, Windows, Windows Vista and other product names are or may be registered trademarks and/or trademarks in the U.S. and/or other countries. The information herein is for informational purposes only and represents the current view of Microsoft Corporation as of the date of this presentation. Because Microsoft must respond to changing market conditions, it should not be interpreted to be a commitment on the part of Microsoft, and Microsoft cannot guarantee the accuracy of any information provided after the date of this presentation. MICROSOFT MAKES NO WARRANTIES, EXPRESS, IMPLIED OR STATUTORY, AS TO THE INFORMATION IN THIS PRESENTATION.
10
print "cat" + 12
print "cat" + 12
using namespace std;
3/4/2011 8:14 PM
© 2007 Microsoft Corporation. All rights reserved. Microsoft, Windows, Windows Vista and other product names are or may be registered trademarks and/or trademarks in the U.S. and/or other countries. The information herein is for informational purposes only and represents the current view of Microsoft Corporation as of the date of this presentation. Because Microsoft must respond to changing market conditions, it should not be interpreted to be a commitment on the part of Microsoft, and Microsoft cannot guarantee the accuracy of any information provided after the date of this presentation. MICROSOFT MAKES NO WARRANTIES, EXPRESS, IMPLIED OR STATUTORY, AS TO THE INFORMATION IN THIS PRESENTATION.
11
Alternative is to name all your types explicitly . Very inefficient.
3/4/2011 8:14 PM
© 2007 Microsoft Corporation. All rights reserved. Microsoft, Windows, Windows Vista and other product names are or may be registered trademarks and/or trademarks in the U.S. and/or other countries. The information herein is for informational purposes only and represents the current view of Microsoft Corporation as of the date of this presentation. Because Microsoft must respond to changing market conditions, it should not be interpreted to be a commitment on the part of Microsoft, and Microsoft cannot guarantee the accuracy of any information provided after the date of this presentation. MICROSOFT MAKES NO WARRANTIES, EXPRESS, IMPLIED OR STATUTORY, AS TO THE INFORMATION IN THIS PRESENTATION.
12
3/4/2011 8:14 PM
© 2007 Microsoft Corporation. All rights reserved. Microsoft, Windows, Windows Vista and other product names are or may be registered trademarks and/or trademarks in the U.S. and/or other countries. The information herein is for informational purposes only and represents the current view of Microsoft Corporation as of the date of this presentation. Because Microsoft must respond to changing market conditions, it should not be interpreted to be a commitment on the part of Microsoft, and Microsoft cannot guarantee the accuracy of any information provided after the date of this presentation. MICROSOFT MAKES NO WARRANTIES, EXPRESS, IMPLIED OR STATUTORY, AS TO THE INFORMATION IN THIS PRESENTATION.
13
F# Provides the Best of Both Worlds
Solution is type inference – compiler works out types mostly without help
Light uncluttered code
3/4/2011 8:14 PM
© 2007 Microsoft Corporation. All rights reserved. Microsoft, Windows, Windows Vista and other product names are or may be registered trademarks and/or trademarks in the U.S. and/or other countries. The information herein is for informational purposes only and represents the current view of Microsoft Corporation as of the date of this presentation. Because Microsoft must respond to changing market conditions, it should not be interpreted to be a commitment on the part of Microsoft, and Microsoft cannot guarantee the accuracy of any information provided after the date of this presentation. MICROSOFT MAKES NO WARRANTIES, EXPRESS, IMPLIED OR STATUTORY, AS TO THE INFORMATION IN THIS PRESENTATION.
14
Dipping your toe in the language
Getting Started
Monodevelop
i = 7
IDE Support
F#/ Visual Studio infer types and offer method suggestions as you type. Can also recall the menu with ctrl-J. Also hover over a value to see its full type, or right click to go to definition.
(Similar to IDLE support but more powerful due to full type inference)
Flow control: if
Functional If statements
let n = 10000
 
val c : string = "big"
// An alternative construct uses the pattern match which is // more flexible
let c2 = match n with
| x when x < 0 -> "negative"
| x when x < 10 -> "single digit"
| _ -> "big"
printf "%d\n" I
#Python
[0, 1, 4, 9, 16, 25, 36, 49, 64, 81]
Collections
 
 
("Fortran",3.0) ; ("COBOL",0.0) ];;
// F# assigns a type signature to each expression which you
// will see explicitly if you are using the fsi F# interactive environment
val primeList : int list = [1; 3; 5; 7; 11; 13; 17; 19]
val primeArray : int [] = [|1; 3; 5; 7; 11; 13; 17; 19|]
val tuple : float * float = (12.3, 4.5)
val tuple2 : string * float = ("F#", 10.0)
val listOfTuples : (string * float) list =
[("F#", 10.0); ("Python", 9.0); ("Java", 5.0); ("Fortran", 3.0);
("COBOL", 0.0)]
Sequence manipulation
primeArray.[0..2] // Elements 0, 1 AND 2
primeArray.[-1] // Won’t work ;( no rhs indexing
// Also works for list but slower
primeList.[3]
// fst and snd (first and second) operators for tuples
snd tuple
List.head primeList
List.tail primeList
The last expression in a function is its return value
Unfinished Functions
# python
FILE PROCESSING EXAMPLE
fp = open (@”c:\tmp\foo.txt”,”r”)
IO libraries are part of DotNet and not strictly an F# concept.
Easy way to process a text file
open System.IO
lines.Length
Sample Output
0.333 0.333
0.308 0.333
0.286 0.444
0.455 0.316
0.400 0.333
0.455 0.462
0.364 0.250
0.400 0.417
0.458 0.417
0.389 0.438
0.385 0.467
0.300 0.353
let rec factorial n =
else if n < 2 then 1
else n * factorial (n-1)
/// Tail recursion friendly version
if n = 1 then mult else _fact (n-1) (mult*n)
if n < 1 then
failwith "bad value"
_fact n 1
More If statements
F# has the familiar constructs for if, while and for that you find in python with some small twists. In keeping with the functional style of programming, the if statement returns a value
let pos f =
 
 
;;
d.[“cat”]
// sys.argv
// Random number generation
let rng = System.Random()
let i = rng.Next(100)
Map/Reduce crash course
The bread-and-butter of a functional programming language is list processing. F# provides many facilities for taking lists and transforming them. Returning to our primes example, we can calculate a list of numbers that appear just before primes by applying a simple n-1 function to our previous primes list. Here we use an anonymous function but we could just as easily define a previous function and use it.
let primeMinusOne = Seq.map (fun n -> n-1) primes;;
 
 
 
let n3 = Seq.filter (endsInThree) primes;;
printf "%A" n3
let sum = Seq.fold (fun sum v -> sum+v) 0 primes;;
val sum : int = 1060
val freq : (int * int) list =
[(1, 19); (2, 17); (1, 13); (2, 12); (3, 8); (1, 7); (2, 5); (3, 2); (5, 1)]
ANT PUZZLE EXAMPLE
ANT
There is an ant which can walk around on a planar grid. The ant can move one space at a time left, right, up or down. That is, from (x, y) the ant can go to (x+1, y), (x-1, y), (x, y+1), and (x, y-1).
Points where the sum of the digits of the x coordinate plus the sum of the digits of the y coordinate are greater than 25 are inaccessible to the ant. For example, the point (59,79) is inaccessible because 5 + 9 + 7 + 9 = 30, which is greater than 25.
How many points can the ant access if it starts at (1000, 1000), including (1000, 1000) itself?
Python Implementation
Python runtime
machine A
machine B
Reached visited 595,393 squares and 148,848 qualify in 5.798332 seconds
Libs
External libraries
Like python, F# makes extensive use of external libraries. These are supplied by a number of dynamically linked libraries DLLs either from the system, from the F# language (technically the FSharp.Core.dll library), or from third party libraries that you choose to add to your project.
The equivalent of the Python import command is open. Once you open the module, you may access types, functions, variables and values in that module.
open System.Text.RegularExpressions
let m = Regex.Match("(cat|dog)*","catcatcatdogcat")
You will find that the editor helps you with the opening process, showing which name spaces are available. Sometimes if you are searching for an operating system library that is not provided by default, Visual Studio will suggest which DLLs should be added to the references section of your project to make the functions available.
Fragments that help
let runProc cmdline =
Visual basic code is often easiest to edit into F#
Don’t be afraid to use muable while getting started
RESOURCES
Driven by assembly debugging
2500 lines of code
3/4/2011 8:14 PM
© 2007 Microsoft Corporation. All rights reserved. Microsoft, Windows, Windows Vista and other product names are or may be registered trademarks and/or trademarks in the U.S. and/or other countries. The information herein is for informational purposes only and represents the current view of Microsoft Corporation as of the date of this presentation. Because Microsoft must respond to changing market conditions, it should not be interpreted to be a commitment on the part of Microsoft, and Microsoft cannot guarantee the accuracy of any information provided after the date of this presentation. MICROSOFT MAKES NO WARRANTIES, EXPRESS, IMPLIED OR STATUTORY, AS TO THE INFORMATION IN THIS PRESENTATION.
56
Read Layout Closeup
3/4/2011 8:14 PM
© 2007 Microsoft Corporation. All rights reserved. Microsoft, Windows, Windows Vista and other product names are or may be registered trademarks and/or trademarks in the U.S. and/or other countries. The information herein is for informational purposes only and represents the current view of Microsoft Corporation as of the date of this presentation. Because Microsoft must respond to changing market conditions, it should not be interpreted to be a commitment on the part of Microsoft, and Microsoft cannot guarantee the accuracy of any information provided after the date of this presentation. MICROSOFT MAKES NO WARRANTIES, EXPRESS, IMPLIED OR STATUTORY, AS TO THE INFORMATION IN THIS PRESENTATION.
57
Densely Packed Region
3/4/2011 8:14 PM
© 2007 Microsoft Corporation. All rights reserved. Microsoft, Windows, Windows Vista and other product names are or may be registered trademarks and/or trademarks in the U.S. and/or other countries. The information herein is for informational purposes only and represents the current view of Microsoft Corporation as of the date of this presentation. Because Microsoft must respond to changing market conditions, it should not be interpreted to be a commitment on the part of Microsoft, and Microsoft cannot guarantee the accuracy of any information provided after the date of this presentation. MICROSOFT MAKES NO WARRANTIES, EXPRESS, IMPLIED OR STATUTORY, AS TO THE INFORMATION IN THIS PRESENTATION.
58
Alignment Level Layout
3/4/2011 8:14 PM
© 2007 Microsoft Corporation. All rights reserved. Microsoft, Windows, Windows Vista and other product names are or may be registered trademarks and/or trademarks in the U.S. and/or other countries. The information herein is for informational purposes only and represents the current view of Microsoft Corporation as of the date of this presentation. Because Microsoft must respond to changing market conditions, it should not be interpreted to be a commitment on the part of Microsoft, and Microsoft cannot guarantee the accuracy of any information provided after the date of this presentation. MICROSOFT MAKES NO WARRANTIES, EXPRESS, IMPLIED OR STATUTORY, AS TO THE INFORMATION IN THIS PRESENTATION.
59
3/4/2011 8:14 PM
© 2007 Microsoft Corporation. All rights reserved. Microsoft, Windows, Windows Vista and other product names are or may be registered trademarks and/or trademarks in the U.S. and/or other countries. The information herein is for informational purposes only and represents the current view of Microsoft Corporation as of the date of this presentation. Because Microsoft must respond to changing market conditions, it should not be interpreted to be a commitment on the part of Microsoft, and Microsoft cannot guarantee the accuracy of any information provided after the date of this presentation. MICROSOFT MAKES NO WARRANTIES, EXPRESS, IMPLIED OR STATUTORY, AS TO THE INFORMATION IN THIS PRESENTATION.
60
Lambda calculus can be called the smallest universal programming language.
Used by Alfonzo Church in 1936 to solve the Entscheidungsproblem
Language grammar 1. <expr> ::= <identifier> 2. <expr> ::= (λ <identifier>. <expr>) 3. <expr> ::= (<expr> <expr>)
f(x) = x + 2  would be expressed in lambda calculus as  λ x. x + 2
Python has lambda functions func = lambda x: x * x
 
Functions are first class values
(you can pass functions to functions, make lists of functions, dictionaries etc)
No state in strict implementations
Deemphasizes variables, loops in favor of other techniques
Lack of state leads to safer programming technique
63
(http://en.wikipedia.org/wiki/Functional_programming)
65
Strong versus Weak Typing
Enforcing type checks makes a language more reliable (but less flexible)
int x = 5.6; // Error
def bwuuHaHaHaHa(x): if x< 0: return “cat” elif x > 0: return 3.1415926 printf “What about %d\n” % bwuuHaHaHaHa(0)
66
67
Map/Reduce
Map
Takes a collection and applies a function to every element in the collection to make a new collection
Reduce
Serially applies a function to each element of a collection incorporating the result of the last function into the next
Appearing in non-functional language settings
Google manages distributed data processing using 1000s of map reduce jobs per day http://labs.google.com/papers/mapreduce.html
68
Monads