About Me Sushant Bhatia, From India/Malawi, Work at Citation Technologies Inc, an Environmental Health & Safety company with Compliance

Similar documents
Introduction to OCaml

Functional Programming. Pure Functional Programming

Programming Paradigms

CSCC24 Functional Programming Scheme Part 2

CMSC 330, Fall 2013, Practice Problems 3

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

COP4020 Programming Languages. Functional Programming Prof. Robert van Engelen

Imperative languages

LECTURE 16. Functional Programming

Functional Programming. Big Picture. Design of Programming Languages

CSCI-GA Scripting Languages

CMSC 330, Fall 2013, Practice Problem 3 Solutions

Functional Programming

CS 11 Ocaml track: lecture 2

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

Functional Programming and Haskell

Functional Programming Languages (FPL)

CSE341: Programming Languages Lecture 9 Function-Closure Idioms. Dan Grossman Winter 2013

OCaml. ML Flow. Complex types: Lists. Complex types: Lists. The PL for the discerning hacker. All elements must have same type.

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

Datatype declarations

JVM ByteCode Interpreter

CSE341: Programming Languages Lecture 9 Function-Closure Idioms. Dan Grossman Fall 2011

Functional Programming for Imperative Programmers

Whom Is This Book For?... xxiv How Is This Book Organized?... xxiv Additional Resources... xxvi

CSC324 Functional Programming Efficiency Issues, Parameter Lists

CS 11 Haskell track: lecture 1

Symbolic Computation and Common Lisp

Two Approaches to Algorithms An Example (1) Iteration (2) Recursion

CMSC 330: Organization of Programming Languages. Functional Programming with Lists

Some Advanced ML Features

Chapter 15. Functional Programming Languages

Overloading, Type Classes, and Algebraic Datatypes

CPS 506 Comparative Programming Languages. Programming Language Paradigm

Programming in Standard ML: Continued

Topic 7: Algebraic Data Types

Chapter 1. Fundamentals of Higher Order Programming

Lists. Michael P. Fourman. February 2, 2010

Introduction to Functional Programming in Racket. CS 550 Programming Languages Jeremy Johnson

Processadors de Llenguatge II. Functional Paradigm. Pratt A.7 Robert Harper s SML tutorial (Sec II)

Tomas Petricek. F# Language Overview

Recap: Functions as first-class values

Programming Systems in Artificial Intelligence Functional Programming

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

CS Lectures 2-3. Introduction to OCaml. Polyvios Pratikakis

The Typed Racket Guide

Mini-ML. CS 502 Lecture 2 8/28/08

CMSC330. Objects, Functional Programming, and lambda calculus

Typed Racket: Racket with Static Types

F# - LISTS. In this method, you just specify a semicolon-delimited sequence of values in square brackets. For example

COSE212: Programming Languages. Lecture 4 Recursive and Higher-Order Programming

Functional Programming. Overview. Topics. Definition n-th Fibonacci Number. Graph

Functional programming Primer I

Unit #2: Recursion, Induction, and Loop Invariants

CSC/MAT-220: Lab 6. Due: 11/26/2018

A Brief Introduction to Standard ML

CSc 372 Comparative Programming Languages

Class 6: Efficiency in Scheme

CSCI 2041: First Class Functions

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

Ozyegin University CS 321 Programming Languages Sample Problems 05

Lecture 5: Lazy Evaluation and Infinite Data Structures

Answers to review questions from Chapter 2

Programming Languages and Techniques (CIS120)

CSc 372. Comparative Programming Languages. 8 : Haskell Function Examples. Department of Computer Science University of Arizona

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

List Functions, and Higher-Order Functions

Functional Programming

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

INTRODUCTION TO HASKELL

Cunning Plan. One-Slide Summary. Functional Programming. Functional Programming. Introduction to COOL #1. Classroom Object-Oriented Language

F# - QUICK GUIDE F# - OVERVIEW

Principles of Programming Languages Topic: Functional Programming Professor L. Thorne McCarty Spring 2003

CMSC 330: Organization of Programming Languages. Functional Programming with Lists

RECURSION. Problem Solving with Computers-II 6

02157 Functional Programming Lecture 2: Functions, Basic Types and Tuples

Haske k ll An introduction to Functional functional programming using Haskell Purely Lazy Example: QuickSort in Java Example: QuickSort in Haskell

Functional Programming

Haskell through HUGS THE BASICS

Programming Languages and Techniques (CIS120)

COSE212: Programming Languages. Lecture 3 Functional Programming in OCaml

Data Structures And Algorithms

Chapter 15. Functional Programming Languages

Common LISP Tutorial 1 (Basic)

Functional Programming. Introduction To Cool

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

An introduction introduction to functional functional programming programming using usin Haskell

Functional Programming. Pure Functional Languages

Organization of Programming Languages CS3200/5200N. Lecture 11

CS152: Programming Languages. Lecture 7 Lambda Calculus. Dan Grossman Spring 2011

Programovací jazyky F# a OCaml. Chapter 3. Composing primitive types into data

Unit #3: Recursion, Induction, and Loop Invariants

News. Programming Languages. Complex types: Lists. Recap: ML s Holy Trinity. CSE 130: Spring 2012

Lecture 10: Recursion vs Iteration

Whereweare. CS-XXX: Graduate Programming Languages. Lecture 7 Lambda Calculus. Adding data structures. Data + Code. What about functions

CPL 2016, week 10. Clojure functional core. Oleg Batrashev. April 11, Institute of Computer Science, Tartu, Estonia

CompSci 220. Programming Methodology 12: Functional Data Structures

Streams. CS21b: Structure and Interpretation of Computer Programs Spring Term, 2004

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

Programmazione Avanzata

Transcription:

About Me Sushant Bhatia, From India/Malawi, Work at Citation Technologies Inc, an Environmental Health & Safety company with Compliance Why I chose to do this talk No one else was doing functional programming. I wanted to learn F#. Just started a few weeks ago. 1

Functional programming is essential to know Being added to C# and.net (generics, lambdas) Useful for developing at a higher level. Add to your tool belt Fun 2

Raffle at the end 3

Open VS 2011 VB Programmers? You just got Iterators, Call hierarchy & Global with.net 4.5 New Project & talk about 3 different project types Create F# Application (Property change from Client Profile to full blown profile) Add a New Item Signature File describes namespace, modules, types & members in corresponding implementation file Add a new.fs file Show UP / DOWN of file order. Compilation order = type inference Remove added.fs file Demo Hello World let msg = Hello World Build Run -> Nothing happens ENTER) Talk about F# Interactive (REPL Read Evaluate Print Loop) (ALT + 4

Type msg;; in Interactive Add print %s msg Run app (F5) Clear Demo Hello World 2 open System Console.WriteLine Hello World (F5) clear Talk about let and how F# values are immutable F# is case sensitive & whitespace matters Comments -> //, ///, (* *) Demo Greatest Common Denominator let rec gcd x y = if y = 0 then x else gcd y (x % y) Hover over gcd defintion to show inference occurs printfn "%i" (gcd 100 6) clear Demo Other things in F# int, float, BigInt (I) 2 + 2;; shows val it : int = 4 (this is an unnamed expression) let my x = if x > 5 then printfn "Cool!" else let db = "Something" printfn "%i %s" x db () clear 4

5

Unit is a concrete representation of void Ignore function swallows a functions return value Tuples provide a convenient way to return multiple values from a function Tuples fst, snd to get values from a tuple. Can also bind as such let mytuple = (1, 2, 3) let x, y, z = mytuple let divrem a b = let x = a / b let y = a % b (x, y) let s = divrem 10 2 Lists Cons (:: ) adds to head of list, append (@) joins two lists List ranges created [1.. 10], [1.. 10.. 100] List comprehension use yield statement within [ and ] Option represents a value that may or may not exist let resolve x = match x with 6

Option.None -> "Zero" Option.Some(30) -> "What what what" _ -> "Meh" // try 6 and 633 let istherea5 = List.tryFind (fun x -> x%633 = 0) [10.. 10.. 100] > resolve 6

For multi file projects, code must be organized into modules or namespaces Create a second fs file. Program.fs namespace Widgets module Program = let Sqr x = x * x module NotMath = let Name = "Sushant Bhatia" type Suit = Club Diamond Heart Spade Octagon File1.fs 7

module File1 let result x = Widgets.Program.Sqr x > printfn "%A" printfn "%s" Widgets.Program.NotMath.Name result 5; let mycardtype = Widgets.Suit.Club let getmatch cardtype = match cardtype with Widgets.Club -> "Its a club" Widgets.Diamond -> "its a diamond" Widgets.Heart -> "Its a heart" Widgets.Spade -> "Its a spade" _ -> "Its a what? Cheater!" (getmatch mycardtype) > printfn "%s" Namespaces cannot directly contain values and functions. Values and functions must be included in modules, and modules are included in namespaces. Namespaces can contain types, modules. 7

DEMO Forward composition operator joins functions together let sqr (x : int) = x * x let tostring (x : int) = x.tostring() let strlen (x : string) = x.length let lenofsqr = sqr >> tostring >> strlen sqr 100 lenofsqr 100 There is also a Pipe Backward (< ) and backward composition (<<) operator 8

Rules are checked in the order they are declared. NoMatch -> MatchFailureException Compiler will issue warning when matches are missing SEE DEMO FROM Module & Namespace 9

SEE DEMO FROM Module & Namespace DEMO BINARY TREES type BinaryTree = Node of int * BinaryTree * BinaryTree Empty let rec printinorder tree = match tree with Node (data, left, right) -> printinorder left printfn "Node %d" data printinorder right Empty -> () (* 2 / \ 1 4 / \ 3 5 10

*) let example = Node(2, Node(1, Empty, Empty), Node(4, Node(3, Empty, Empty), Node(5, Empty, Empty) ) ) printinorder example 10

11

Program is a description of a specific computation Ignore how & focus on what Program is a black box for obtaining output from input Program is like a function 12

Originated with Lambda calculus = formal system developed in 1930s investigate function definition, application & recursion 13

Still quite complex so lets break it down 14

http://dev.bennage.com/blog/2010/09/06/what-is-functional-programming/ 15

Treat functions as first class objects. 16

17

An expression is said to be referentially transparent if it can be replaced with its value without changing the behavior of a program. Memoization is optimization by having function calls avoid repeating the calculations of results for previously processed inputs. DEMO: Memoization open System let sqr i : int = i * i let memoize f = let cache = ref Map.empty fun x -> match (!cache).tryfind(x) with Some res -> res None -> let res = f x cache := (!cache).add(x,res) res let memoizedappend = 18

memoize (fun input -> printfn "Working out the value for '%A'" input String.concat ", " [ for i in 0.. input -> sprintf "%d: %i" i (sqr i) ]) Console.WriteLine(memoizedAppend(10)) Console.WriteLine("\r\n----\r\n") Console.WriteLine(memoizedAppend(10)) Console.WriteLine("\r\n----\r\n") Console.WriteLine(memoizedAppend(5)) Console.WriteLine("\r\n----\r\n") Console.WriteLine(memoizedAppend(10)) 18

Using recursion can be expensive for large numbers of iterations due to declaring the stack over and over. Process is terminated due to StackOverflowException. For this purpose, know when to use Tail Recursion Tail calls drop the current stack frame before making the recursive call. Thus function will execute faster, indefinitely and no stackoverflowexception. The CLR has an IL instruction specifically to help with tail recursion: the tail. IL prefix. The tail. instruction tells the CLR it can discard the caller s method state prior to making the associated call. DEMO: Fibonacci let rec fib n = if n < 2I then 1I else fib (n-2i) + fib(n-1i) let fibtail = Seq.unfold (fun (x, y) -> Some(x, (y, x+y)) ) (0I,1I) fibtail > Seq.nth 50000 19

Currying transforms a function that has more than 1 parameter into a series of embedded functions each with 1 parameter. Can only curry parameters from left to right DEMO: sizeofdir open System.IO let sizeofdir folder pattern = let getfiles folder = Directory.GetFiles(folder, pattern, SearchOption.AllDirectories) let totalsize = folder > getfiles > Array.map (fun file -> new FileInfo(file)) > Array.map (fun info -> info.length) > Array.sum totalsize let DellFolder = sizeofdir "C:\\DELL" DellFolder "*.txt" 20

DEMO: Netflix open System.Data.Services.Client open Microsoft.FSharp.Data.TypeProviders // Use the OData type provider to access the Netflix catalog. [<Generate>] type Catalog = ODataService<"http://odata.netflix.com/Catalog/"> let netflix = Catalog.GetDataContext() // Query Netflix for all titles containing the word "Avatar" let titles = query { for t in netflix.titles do where (t.name.contains "naruto") } titles > Seq.iter (fun i -> printfn "%A - %s %i" i.id i.name i.awards.count) 21

Console.WriteLine(memoizedAppend(10)) Console.WriteLine("\r\n----\r\n") Console.WriteLine(memoizedAppend(10)) Console.WriteLine("\r\n----\r\n") Console.WriteLine(memoizedAppend(5)) Console.WriteLine("\r\n----\r\n") Console.WriteLine(memoizedAppend(10)) DEMO: Units of Measure [<Measure>] type kg [<Measure>] type s [<Measure>] type m [<Measure>] type N = (kg * m)/(s^2) let gravityonearth = 9.81<m/(s^2)> let dropheight = 1000.0<m> let impactspeed = sqrt(2.0 * gravityonearth * dropheight) let force :float<n> = 80.0<kg> * gravityonearth DEMO ASYNC open System open System.Net open System.Text.RegularExpressions let websites = ["http://www.weather.gov"; "http://msdn.microsoft.com/en-us/"; "http://fsharp-euler.wikispaces.com"] let regtitle = new Regex(@"\<title\>([^\<]+)\</title\>") let WriteLinePageTitle result = printfn "%A" (regtitle.match result).groups.[0].value let AsyncIntroSingle website = async { let client = new WebClient() let! result = client.asyncdownloadstring(uri(website)) 21

do WriteLinePageTitle result } > Async.StartImmediate websites > List.iter (fun x -> AsyncIntroSingle x) 21

http://projecteuler.net/problems http://fsharp-euler.wikispaces.com/ //If we list all the natural numbers below 10 that are multiples of 3 or 5, we get 3, 5, 6 and 9. The sum of these multiples is 23. //Find the sum of all the multiples of 3 or 5 below 1000. let lst = [1..1000] > List.filter (fun x -> x%3 = 0 x%5 = 0) > List.sum //Each new term in the Fibonacci sequence is generated by adding the previous two terms. By starting with 1 and 2, the first 10 terms will be: // 1, 2, 3, 5, 8, 13, 21, 34, 55, 89,... //By considering the terms in the Fibonacci sequence whose values do not exceed four million, find the sum of the even-valued terms. let fibtail = Seq.unfold (fun (x, y) -> Some(x, (y, x+y)) ) (0I,1I) let problem2 = fibtail > Seq.takeWhile (fun x -> x < 4000000I) > Seq.sumBy (fun x -> if x%2i = 0I then x else 0I) 22

Read Practice Solve real world problems with it 23

24