Learning F# and the Functional Point of View. Robert Pickering, LexiFi

Similar documents
Reactive programming, WinForms,.NET. Björn Dagerman

Object-oriented programming. and data-structures CS/ENGRD 2110 SUMMER 2018

Functional Programming. Pure Functional Programming

CMSC330 Spring 2014 Midterm 2 Solutions

ITT8060: Advanced Programming (in F#)

Abram Hindle Kitchener Waterloo Perl Monger October 19, 2006

CSCI-GA Scripting Languages

Notes from a Short Introductory Lecture on Scala (Based on Programming in Scala, 2nd Ed.)

Variables and Bindings

Recursion CSCI 136: Fundamentals of Computer Science II Keith Vertanen Copyright 2011

Recap: Functions as first-class values

Controls Structure for Repetition

Introduction to programming with Python

FUNCTIONAL PROGRAMMING

Tomas Petricek. F# Language Overview

Introduction to the course and basic programming concepts

Hands-On Lab. Introduction to F# Lab version: Last updated: 12/10/2010. Page 1

Better typing errors for OCaml. Arthur Charguéraud Inria

CSE 413 Final Exam. June 7, 2011

CMSC330 Spring 2014 Midterm #2. Score 1 OCaml types & type

Lecture 1 - Introduction (Class Notes)

Pace University. Fundamental Concepts of CS121 1

Ch 9: Control flow. Sequencers. Jumps. Jumps

Recursion. Overview. Mathematical induction. Hello recursion. Recursion. Example applications. Goal: Compute factorial N! = 1 * 2 * 3...

Lwt: a Cooperative Thread Library

CMSC330 Spring 2016 Midterm #1 9:30am/12:30pm/3:30pm

Java Coding style guide 1. Java. Coding Style Guide. (July 2015)

Introduction to Concepts in Functional Programming. CS16: Introduction to Data Structures & Algorithms Spring 2017

CMSC 330: Organization of Programming Languages. OCaml Imperative Programming

Introduce C# as Object Oriented programming language. Explain, tokens,

Introduction to OCaml

Crash Course in Java. Why Java? Java notes for C++ programmers. Network Programming in Java is very different than in C/C++

The F# Team Microsoft

(Provisional) Lecture 22: Rackette Overview, Binary Tree Analysis 10:00 AM, Oct 27, 2017

Programming Languages and Techniques (CIS120)

Lab 7: OCaml 12:00 PM, Oct 22, 2017

F# for Scientists. Jon Harrop Flying Frog Consultancy Ltd. Foreword by Don Syme A JOHN WILEY & SONS, INC., PUBLICATION WILEY

NOTE: Answer ANY FOUR of the following 6 sections:

OCaml Data CMSC 330: Organization of Programming Languages. User Defined Types. Variation: Shapes in Java

Functional Programming and Parallel Computing

News. CSE 130: Programming Languages. Environments & Closures. Functions are first-class values. Recap: Functions as first-class values

Internet Technology 2/7/2013

Intro. Scheme Basics. scm> 5 5. scm>

Index. Cambridge University Press Functional Programming Using F# Michael R. Hansen and Hans Rischel. Index.

Advanced Python. Executive Summary, Session 1

CMSC330 Fall 2014 Midterm 2 Solutions

Recap. Recap. If-then-else expressions. If-then-else expressions. If-then-else expressions. If-then-else expressions

CSE 413 Final Exam Spring 2011 Sample Solution. Strings of alternating 0 s and 1 s that begin and end with the same character, either 0 or 1.

Recursion. Fundamentals of Computer Science

Closures. Mooly Sagiv. Michael Clarkson, Cornell CS 3110 Data Structures and Functional Programming

Why OCaml? Introduction to Objective Caml. Features of OCaml. Applications written in OCaml. Stefan Wehr

! Broaden your language horizons! Different programming languages! Different language features and tradeoffs. ! Study how languages are implemented

Introduction to Objective Caml

DS 2009: middleware. David Evans

CMSC330 Spring 2016 Midterm #1 9:30am/12:30pm/3:30pm Solution

Lecture 05: Methods. AITI Nigeria Summer 2012 University of Lagos.

Using Scala for building DSL s

About this exam review

Chapter 17 Parallel Work Queues

1007 Imperative Programming Part II

CS52 - Assignment 8. Due Friday 4/15 at 5:00pm.

Introduction to Erlang. Franck Petit / Sebastien Tixeuil

Prerequisites: The student should have programming experience in a high-level language. ITCourseware, LLC Page 1. Object-Oriented Programming in C#

Tuples. CMSC 330: Organization of Programming Languages. Examples With Tuples. Another Example

CMSC 330: Organization of Programming Languages. OCaml Imperative Programming

AP COMPUTER SCIENCE JAVA CONCEPTS IV: RESERVED WORDS

Anonymous Functions CMSC 330: Organization of Programming Languages

CS 321 Programming Languages

Chapter 27 Cluster Work Queues

CS 463 Project 1 Imperative/OOP Fractals

CSE 373 Spring 2010: Midterm #1 (closed book, closed notes, NO calculators allowed)

F# for Industrial Applications Worth a Try?

Typed Racket: Racket with Static Types

Language Proposal: tail

02157 Functional Programming Lecture 1: Introduction and Getting Started

C++: Overview and Features

COMP 110 Programming Exercise: Simulation of the Game of Craps

61A Lecture 2. Wednesday, September 4, 2013

What goes inside when you declare a variable?

CS Lecture 6: Map and Fold. Prof. Clarkson Spring Today s music: Selections from the soundtrack to 2001: A Space Odyssey

Introduction to OCaml

Binary Search and Worst-Case Analysis

Programming Languages and Techniques (CIS120)

Forward recursion. CS 321 Programming Languages. Functions calls and the stack. Functions calls and the stack

Piqi-RPC. Exposing Erlang services via JSON, XML and Google Protocol Buffers over HTTP. Friday, March 25, 2011

Programovací jazyky F# a OCaml. Chapter 6. Sequence expressions and computation expressions (aka monads)

Hard deadline: 3/28/15 1:00pm. Using software development tools like source control. Understanding the environment model and type inference.

Functional Programming in Java. CSE 219 Department of Computer Science, Stony Brook University

CMSC 330, Fall 2013, Practice Problems 3

Outline. What s wrong with Enumerations? Indexing Searching Self-Organizing Vectors Binary Searching Sorting Command line Arguments.

Programovací jazyky F# a OCaml. Chapter 5. Hiding recursion using function-as-values

New programming languages and paradigms

The Actor Model. CSCI 5828: Foundations of Software Engineering Lecture 13 10/04/2016

Variables and data types

Compilers. Type checking. Yannis Smaragdakis, U. Athens (original slides by Sam

Closures. Mooly Sagiv. Michael Clarkson, Cornell CS 3110 Data Structures and Functional Programming

Chapter 11 :: Functional Languages

Intermediate Code Generation

Async. Prof. Clarkson Fall Today s music: It's Gonna be Me by *NSYNC

CS/B.TECH/CSE(New)/SEM-5/CS-504D/ OBJECT ORIENTED PROGRAMMING. Time Allotted : 3 Hours Full Marks : 70 GROUP A. (Multiple Choice Type Question)

Transcription:

Learning F# and the Functional Point of View Robert Pickering, LexiFi http://strangelights.com

Session Objectives Why was F# created? Why learn F#? A taste of the F# language Especially the functional side! A look at some wizzy features F#

Part 1 Why? Why? Why? Why? Why? Why?

I'll let you in on a secret: I'm doing F# simply because it's lots and lots of fun. In a very broad sense of the word: functional programming is fun, OO programming with F# is fun, watching people use F# is fun. One of the wonderful things about F# is that you can actually end up working in your domain. In the zone. With F#, you're not necessarily "just" a programmer! You're likely to also be a probabilistic modeller, or an AutoCAD engineer, or a finance engineer, or a symbolic programmer, or one of many other things. - Don Syme, F# s creator

F# is unique amongst both imperative and declarative languages in that it is the golden middle road where these two extremes converge. F# takes the best features of both paradigms and tastefully combines them in a highly productive and elegant language that both scientists and developers identify with. F# makes programmers better mathematicians and mathematicians better programmers. - Eric Meijer, Forward to Expert F#

Functions are much easier to test than operations that have side effects. For these reasons, functions lower risk. Place as much of the logic of the program as possible into functions, operations that return results with no observable side effects. - Domain Driven Design, Eric Evans

F# frees you of the fluffy pink hand cuffs of C# - Amanda Laucher, Consultant and F# Author

F# - What is it For? F# is a General Purpose language F# is also A Bridge Language A Language Both Researchers and Developers Can Speak Some important domains Scientific data analysis Data mining Domain-specific modeling

F#: The Combination Counts! Scalable Libraries Explorative Succinct Interoperable Statically Typed F# Efficient

F#: Influences OCaml F# C#/.NET Similar core language Similar object model

Part 2 F# the Language...... and the Functional Point of View

Hello World printfn "hello world"

Values & let Bindings let anint = 42 // an integer let astring = "Stringy" // a string let afloat = 13. // a float let alist = ["Collect"; "ion"] // a list of strings let atuple = "one", 2 // a tuple let anobject = new FileInfo(@"c:\src.fs") // a.net object

Functions // a shorter function version let addten = x fun = x x + -> 10 x + 10 // multi parameters and // intermediate results let addthentimestwo x y = let result = x + y result * 2

Function as Values // define a list let list = [1; 2; 3] // define a function let addnine x = x + 9 // pass function to "addnine" to // higher order function "List.map" let result = List.map addnine list

Anonymous Functions // define a list let list = [1; 2; 3] // pass function definition directly to // higher order function "List.map" let result = List.map (fun x -> x + 9) list

Everything s an Expression // bind name to "Robert" // or to "Pickering" let name = if usefirst then "Robert" else "Pickering" // we can bind more than one value at once let name mytuple, value = = if usefirst then "Robert", 1 else "Pickering", 2

Loop With Recursion let cmax = complex 1.0 1.0 // Max complex value let cmin = complex -1.0-1.0 // Min complex value let iterations = 18 // Max iterations let isinmandelbrotset c0 = let rec check n c = (n = iterations) // exit if max iterations // reached (cmin < c) && (c < cmax) // exit if escaped // complex number bounds && check (n + 1) ((c * c) + c0) // recurse! // start recursion check 0 c0

Record Types // a "Person" type definition type Person = { FirstName: string; LastName: string; } // an instance of a "Person" let aperson = { FirstName = "Robert"; LastName = "Pickering"; }

Creating New Records // a single person let single = { FirstName = "Robert"; LastName = "Pickering"; } // create record with different // last name let married = { single with LastName = "Townson"; }

Union Types The Option Type // The pre-defined option type type Option<'a> = Some of 'a None // constructing options let somevalue = Some 1 let novalue = None // pattern matching over options let convert value = match value with Some x -> Printf.sprintf "Value: %i" x None -> "No value"

Union Types - Trees // a binary tree definition type BinaryTree<'a> = Node of BinaryTree<'a> * BinaryTree<'a> Leaf of 'a // walk the tree collection values let rec collectvalues acc tree = match tree with Node(ltree, rtree) -> // recursively walk the left tree let acc = collectvalues acc ltree // recursively walk the right tree collectvalues acc rtree Leaf value -> value :: acc // add value to accumulator

Using the Tree // define a tree let tree = Node( Node(Leaf 1, Leaf 2), Node(Leaf 3, Leaf 4)) // recover all values from the leaves let values = collectvalues [] tree

.NET Objects open System.Windows.Forms let form = // create a new form instance let form = new Form(Text = "Hello") // create a couple of controls let textbox = new TextBox(Text = "Hello") // add the controls form.controls.add(textbox) // return the form form form.show()

Part 3 A brief look at...

... Language Oriented Programming A Command Line Argument Parse

Ever Written an Arg Parser in C#? Was it an enjoyable experience? Or was it more like: static void Main(string[] args) { int reps = 0; for (int index = 0; index < args.length; index++) { switch (args[index]) { case "-reps": int nextarg = index + 1; if (nextarg < args.length) { if (!int.tryparse(args[nextarg], out reps)) { throw new Exception("Agrument not an integer"); } } else { throw new Exception("Argument expected"); } //... etc....

let argdefs = [ "-outfile", Arg.String(fun x -> outfile := x), "The output file to be used"; "-reps", Arg.Int(fun x -> reps := x), "The number of repetitions"; "-res", Arg.Float(fun x -> res := x), "Sets the value resolution"; ]

An F# Command-Line Argument Parse DEMO

... Concurrency Calling Web Services Asynchronously

Calling Web Services Demonstration of calling a web service synchronously and asynchronously using workflows This demonstration will analyse: Changes in the code required How the results are effected How is performance effected

Asynchronous Workflows and Web Synchronous Services let getatoms() = let pt = new PeriodicTableWS.periodictable() let atoms = pt.getatoms() let atoms = getnodecontentslist atoms "/NewDataSet/Table/ElementName" atoms Asynchronous let getatoms = async { let pt = new PeriodicTableWS.periodictable() let! atoms = pt.asyncgetatoms() let atoms = getnodecontentslist atoms "/NewDataSet/Table/ElementName" return atoms }

Where did the Async Come From? The programmer must add these to the web service proxies type PeriodicTableWS.periodictable with member ws.asyncgetatoms() = Async.BuildPrimitive(ws.BeginGetAtoms, ws.endgetatoms) type PeriodicTableWS.periodictable with member ws.asyncgetatomicweigh(s) = Async.BuildPrimitive(s, ws.begingetatomicweight, ws.endgetatomicweight)

Calling a web service DEMO

Interpreting the Results Synchronous [.NET Thread 1]Get Element Data List [.NET Thread 1]Got 112 Elements [.NET Thread 1]Get Data For: Actinium [.NET Thread 1]Actinium: 227 [.NET Thread 1]Get Data For: Aluminium [.NET Thread 1]Aluminium: 26.9815 [.NET Thread 1]Get Data For: Americium [.NET Thread 1]Americium: 243 [.NET Thread 1]Get Data For: Antimony [.NET Thread 1]Antimony: 121.75 [.NET Thread 1]Get Data For: Argon [.NET Thread 1]Argon: 39.948 [.NET Thread 1]Get Data For: Arsenic...... Asynchronous [.NET Thread 1]Get Element Data List [.NET Thread 6]Got 112 Elements [.NET Thread 11]Get Data For: Actinium [.NET Thread 11]Get Data For: Aluminium [.NET Thread 10]Get Data For: Americium [.NET Thread 11]Get Data For: Antimony [.NET Thread 11]Get Data For: Argon... [.NET Thread 6]Actinium: 227 [.NET Thread 6]Aluminium: 26.9815 [.NET Thread 6]Americium: 243 [.NET Thread 6]Antimony: 121.75 [.NET Thread 6]Arsenic: 74.9216 [.NET Thread 6]Astatine: 210...

The Timings Synchronous Asynchronous Real CPU Real CPU 48.976 00.187 24.571 00.142 48.270 00.109 24.432 00.156 54.240 00.078 24.641 00.218

Part 4 The End Bit

msdn.microsoft.com/fsharp/

F# Resources MDSN Resource center: http://msdn.microsoft.com/fsharp/ User forums: http://cs.hubfs.net/forums Blogs (there are lots of others!): http://blogs.msnd.com/dsyme http://strangelights.com/blog Samples on the web: http://code.msdn.microsoft.com/fsharpsamples http://code.google.com/hosting/search?q=label:fsharp http://codeplex.com/project/projectdirectory.aspx?tagname=f%23 Source available with the distribution: %ProgramFiles%\FSharp-1.9.6.2\source

Books about F#

Questions?!?