SlideShare une entreprise Scribd logo
1  sur  28
@kitlovesfsharp www.github.com/misterspeedy
F# For an Easy Life!
Kit Eason
F# in a nutshell
 Microsoft first class supported language for .NET
 Supports OO and functional paradigms
 Compiles to CLI like C#, VB.Net
 First class citizen in VS2010 and VS2012 (free!). (Also in 2013 preview)
 Open source, runs on Mono (use Xamarin)
 Strongly typed
F# functions
 Use ‘let’ to declare functions and values
let add x y =
x + y
 The return value of the function is the last value calculated (no ‘return’
statement
let add x y =
x + y
 Types are inferred (at design time)
 Argument lists don’t have brackets
F# Interactive (FSI)
> let add x y =
x + y;;
val add : x:int -> y:int -> int
> add 3 4;;
val it : int = 7
>
• Use F# interactive to define and try out functions
Calculating present value
> let presentValue fv r t =
fv * (1.+r) ** (-t);;
val presentValue : fv:float -> r:float -> t:float -> float
> presentValue 2000.0 0.07 10.;;
val it : float = 1016.698584
>
• Formulae can be represented very directly
The ‘map’ function
 Take some collection (array, list, IEnumerable)
 For every value calculate and return some other value
 Result is another array/list/IEnumerable containing the results
let someSquares min max =
// This generates an array from min to max:
let numbers = [|min..max|]
Array.map (fun x -> x * x) numbers
val someSquares : min:int -> max:int -> int []
> someSquares 100 110;;
val it : int [] =
[|10000; 10201; 10404; 10609; 10816; 11025; 11236; 11449; 11664;
11881;
12100|]
>
The forward pipe operator |>
 Takes the output from the preceding function
 Places it into the (last) parameter of the following function
let add x y =
x + y
let multiply x y =
x * y
val add : x:int -> y:int -> int
val multiply : x:int -> y:int -> int
> add 2 3 |> multiply 5;;
val it : int = 25
>
The forward pipe operator |> (2)
 Comes into its own when dealing with collections
let rootMeanSquare min max =
[|min..max|]
|> Array.map (fun x -> x * x)
|> Array.average
|> sqrt
val rootMeanSquare : min:float -> max:float -> float
> rootMeanSquare -10.0 10.0;;
val it : float = 6.055300708
>
The ‘mapi’ function
 Like ‘map’ but provides you with an index value 0, 1, 2 etc.
let someAdditions min max =
[|min..max|]
|> Array.mapi (fun i x -> i + x)
val someAdditions : min:int -> max:int -> int []
> someAdditions 100 110;;
val it : int [] = [|100; 102; 104; 106; 108; 110; 112;
114; 116; 118; 120|]
>
Calculating present value of a cashflow
 Calculate the present value of a cashflow starting at time 0
let presentValue fv r t =
fv * (1.+r) ** (-t)
let cfPresentValue cf r =
cf
|> Array.mapi (fun t amt -> presentValue amt r (float(t)))
|> Array.sum
val presentValue : fv:float -> r:float -> t:float -> float
val cfPresentValue : cf:float [] -> r:float -> float
> cfPresentValue [|1000.0; 2000.0; 2500.0|] 0.07;;
val it : float = 5052.755699
>
Great Circle Distance
Unit Testing and TDD
 Create a new F# library project
 Use Nuget to bring in FSUnit
 Add GreatCircleTests.fs
module GreatCircleTests
open NUnit.Framework
open FsUnit
Write a trivial test!
module GreatCircleTests
open NUnit.Framework
open FsUnit
[<TestFixture>]
type ``Given the GreatCircleDistance function``() =
[<Test>]
member x.``The function returns 0 for a journey between the same
points``() =
let expected = 0.
let actual = GreatCircle.Distance 45. 50. 45. 50.
actual |> should equal expected
Pass the test!
module GreatCircle
let Distance lat1 long1 lat2 long2 =
0.
What’s the next simplest test?
[<Test>]
member x.``The function returns 20014 km for a journey between the poles``() =
let expected = 20014.
let actual = GreatCircle.Distance -90. 0. 90. 0.
actual |> should equal expected
We’re gonna need an algorithm!
var R = 6371; // km
var dLat = (lat2-lat1).toRad();
var dLon = (lon2-lon1).toRad();
var lat1 = lat1.toRad();
var lat2 = lat2.toRad();
var a = Math.sin(dLat/2) * Math.sin(dLat/2) +
Math.sin(dLon/2) * Math.sin(dLon/2) * Math.cos(lat1) * Math.cos(lat2);
var c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1-a));
var d = R * c;
How’s this?
open System
let Distance lat1 lon1 lat2 lon2 =
let EarthRadius = 6378.1
let Deg2Rad deg =
deg * Math.PI / 180.
let lat1r = lat1 |> Deg2Rad
let lat2r = lat2 |> Deg2Rad
let dLat = lat2 - lat1 |> Deg2Rad
let dLon = lon2 - lon1 |> Deg2Rad
let a = (sin(dLat/2.) ** 2.) +
(sin(dLon/2.) ** 2.) * cos(lat1r) * cos(lat2r)
let c = 2. * atan2 (sqrt(a)) (sqrt(1.-a))
c * EarthRadius
Whuuuuuuuuuuuuuuuuuu?
------ Test started: Assembly: FSUnitTestingExample.dll ------
Test 'GreatCircleTests+Given the GreatCircleDistance function.The
function returns 20014 km for a journey between the poles' failed:
Expected: 20014.0d
But was: 20037.392103861061d
at FsUnit.TopLevelOperators.should[a,a](FSharpFunc`2 f, a x,
Object y)
C:CodeVS2012FSUnitTestingExampleFSUnitTestingExampleGre
atCircleTests.fs(28,0): at GreatCircleTests.Given the
GreatCircleDistance function.The function returns 20014 km for a
journey between the poles()
1 passed, 1 failed, 0 skipped, took 0.37 seconds (NUnit 2.6.1).
They all laughed at Christopher Columbus…
[<TestFixture>]
type ``Given the GreatCircleDistance function``() =
let margin = 0.003
[<Test>]
member x.``The function returns 0 for a journey between the same points``() =
let expected = 0.
let actual = GreatCircle.Distance 45. 50. 45. 50.
actual |> should (equalWithin margin) expected
[<Test>]
member x.``The function returns 20014 km for a journey between the poles``() =
let expected = 20014.
let actual = GreatCircle.Distance -90. 0. 90. 0.
let error = expected * margin
actual |> should (equalWithin error) expected
Further tests better added as cases
// Travel no distance:
[<TestCase(0., 0., 0., 0., 0.)>]
// Travel along the equator eastwards for 90 degrees:
[<TestCase(0., 0., 0., 90., 10018.79)>]
// Travel along the equator westwards for 90 degrees:
[<TestCase(0., 0., 0., -90., 10018.79)>]
// Travel along the equator eastwards for 180 degrees:
[<TestCase(0., 0., 0., 180., 20037.58)>]
// Travel along the equator westwards for 180 degrees:
[<TestCase(0., 0., 0., -180., 20037.58)>]
// Travel along the meridian northwards 90 degrees:
[<TestCase(0., 0., 90., 0., 10018.79)>]
// Travel along the meridian soutwards 90 degrees:
[<TestCase(0., 0., -90., 0., 10018.79)>]
// Travel from Farnham to Reigate:
[<TestCase(51.214, -0.799, 51.230, -0.188, 42.6)>]
// Travel from London to Sidney Australia:
[<TestCase(51.51, -0.13, -33.86, 151.21, 16998.)>]
member t.``the function returns the right result``(lat1, long1, lat2, long2, expected) =
let actual = GreatCircle.Distance lat1 long1 lat2 long2
let error = expected * margin
actual |> should (equalWithin error) expected
Information-Rich Programming
 Bring large, structured data sources into the code in a type-safe way…
with Intellisense!
 Implemented by ‘Type Providers’
 Introduced with F#3.0 (VS2012)
 Code-gen free!
Information Rich Programming
22
Freebase
Nuget and Fsharp.Data
Get airports and locations
/// Gets airports between a specified start and end index (to facilitate paged access).
let GetAirportsPaged startIndex pageSize =
query {
for airport in dc.Transportation.Aviation.Airports do
where ( airport.Geolocation <> null
&& airport.Geolocation.Latitude.HasValue
&& airport.Geolocation.Longitude.HasValue
)
skip startIndex
take pageSize
select (airport.Name,
airport.Geolocation.Latitude.Value,
airport.Geolocation.Longitude.Value)
}
|> Array.ofSeq
|> Array.map (fun (name, lat, long) -> { Name = name; Lat = lat; Long = long })
Get airports and locations (2)
/// Gets all airports from Freebase which have a defined location.
let GetAllAirports pageSize =
let rec getPage startIndex acc =
let page = GetAirportsPaged startIndex pageSize
if page.Length > 0 then
Array.append acc (getPage (startIndex+pageSize) page)
else
acc
getPage 0 [||]
Get closest airports
/// Gets the closest n airports to the given airport.
let GetClosest target count airportList =
airportList
|> Array.map (fun airport -> airport, (DistanceBetween
(airport.Lat) (airport.Long) (target.Lat) (target.Long)))
|> Array.sortBy (fun (airport, distance) -> distance)
|> Seq.truncate count
|> Array.ofSeq
Get closest airports to a named airport
/// Gets airports near an airport specified by name.
let GetAirportsNear name airportList =
let target = airportList
|> Array.tryFind (fun airport -> airport.Name.Contains(name))
if target.IsSome then
airportList
|> GetClosest target.Value 20
|> Array.iter (fun (airport, distance) -> printfn "%s - %f km" airport.Name distance)
else
printfn "Could not find %s" name

Contenu connexe

Tendances

Introduction to functional programming using Ocaml
Introduction to functional programming using OcamlIntroduction to functional programming using Ocaml
Introduction to functional programming using Ocamlpramode_ce
 
Learn a language : LISP
Learn a language : LISPLearn a language : LISP
Learn a language : LISPDevnology
 
Java Foundations: Lists, ArrayList<T>
Java Foundations: Lists, ArrayList<T>Java Foundations: Lists, ArrayList<T>
Java Foundations: Lists, ArrayList<T>Svetlin Nakov
 
Java simple programs
Java simple programsJava simple programs
Java simple programsVEERA RAGAVAN
 
Collection frame work
Collection  frame workCollection  frame work
Collection frame workRahul Kolluri
 
Lecture 5, c++(complete reference,herbet sheidt)chapter-15
Lecture 5, c++(complete reference,herbet sheidt)chapter-15Lecture 5, c++(complete reference,herbet sheidt)chapter-15
Lecture 5, c++(complete reference,herbet sheidt)chapter-15Abu Saleh
 
Vector class in C++
Vector class in C++Vector class in C++
Vector class in C++Jawad Khan
 
Laziness, trampolines, monoids and other functional amenities: this is not yo...
Laziness, trampolines, monoids and other functional amenities: this is not yo...Laziness, trampolines, monoids and other functional amenities: this is not yo...
Laziness, trampolines, monoids and other functional amenities: this is not yo...Mario Fusco
 
The Ring programming language version 1.3 book - Part 25 of 88
The Ring programming language version 1.3 book - Part 25 of 88The Ring programming language version 1.3 book - Part 25 of 88
The Ring programming language version 1.3 book - Part 25 of 88Mahmoud Samir Fayed
 
Composing an App with Free Monads (using Cats)
Composing an App with Free Monads (using Cats)Composing an App with Free Monads (using Cats)
Composing an App with Free Monads (using Cats)Hermann Hueck
 
Atomically { Delete Your Actors }
Atomically { Delete Your Actors }Atomically { Delete Your Actors }
Atomically { Delete Your Actors }John De Goes
 
If You Think You Can Stay Away from Functional Programming, You Are Wrong
If You Think You Can Stay Away from Functional Programming, You Are WrongIf You Think You Can Stay Away from Functional Programming, You Are Wrong
If You Think You Can Stay Away from Functional Programming, You Are WrongMario Fusco
 
Chapter i(introduction to java)
Chapter i(introduction to java)Chapter i(introduction to java)
Chapter i(introduction to java)Chhom Karath
 
Java 8 Stream API. A different way to process collections.
Java 8 Stream API. A different way to process collections.Java 8 Stream API. A different way to process collections.
Java 8 Stream API. A different way to process collections.David Gómez García
 
Scala - where objects and functions meet
Scala - where objects and functions meetScala - where objects and functions meet
Scala - where objects and functions meetMario Fusco
 
Operator overloading (binary)
Operator overloading (binary)Operator overloading (binary)
Operator overloading (binary)Ramish Suleman
 
Java Foundations: Maps, Lambda and Stream API
Java Foundations: Maps, Lambda and Stream APIJava Foundations: Maps, Lambda and Stream API
Java Foundations: Maps, Lambda and Stream APISvetlin Nakov
 
Arrry structure Stacks in data structure
Arrry structure Stacks  in data structureArrry structure Stacks  in data structure
Arrry structure Stacks in data structurelodhran-hayat
 

Tendances (20)

Introduction to functional programming using Ocaml
Introduction to functional programming using OcamlIntroduction to functional programming using Ocaml
Introduction to functional programming using Ocaml
 
Learn a language : LISP
Learn a language : LISPLearn a language : LISP
Learn a language : LISP
 
.net progrmming part2
.net progrmming part2.net progrmming part2
.net progrmming part2
 
Java Foundations: Lists, ArrayList<T>
Java Foundations: Lists, ArrayList<T>Java Foundations: Lists, ArrayList<T>
Java Foundations: Lists, ArrayList<T>
 
Java simple programs
Java simple programsJava simple programs
Java simple programs
 
Collection frame work
Collection  frame workCollection  frame work
Collection frame work
 
Lecture 5, c++(complete reference,herbet sheidt)chapter-15
Lecture 5, c++(complete reference,herbet sheidt)chapter-15Lecture 5, c++(complete reference,herbet sheidt)chapter-15
Lecture 5, c++(complete reference,herbet sheidt)chapter-15
 
Vector class in C++
Vector class in C++Vector class in C++
Vector class in C++
 
Laziness, trampolines, monoids and other functional amenities: this is not yo...
Laziness, trampolines, monoids and other functional amenities: this is not yo...Laziness, trampolines, monoids and other functional amenities: this is not yo...
Laziness, trampolines, monoids and other functional amenities: this is not yo...
 
The Ring programming language version 1.3 book - Part 25 of 88
The Ring programming language version 1.3 book - Part 25 of 88The Ring programming language version 1.3 book - Part 25 of 88
The Ring programming language version 1.3 book - Part 25 of 88
 
MTL Versus Free
MTL Versus FreeMTL Versus Free
MTL Versus Free
 
Composing an App with Free Monads (using Cats)
Composing an App with Free Monads (using Cats)Composing an App with Free Monads (using Cats)
Composing an App with Free Monads (using Cats)
 
Atomically { Delete Your Actors }
Atomically { Delete Your Actors }Atomically { Delete Your Actors }
Atomically { Delete Your Actors }
 
If You Think You Can Stay Away from Functional Programming, You Are Wrong
If You Think You Can Stay Away from Functional Programming, You Are WrongIf You Think You Can Stay Away from Functional Programming, You Are Wrong
If You Think You Can Stay Away from Functional Programming, You Are Wrong
 
Chapter i(introduction to java)
Chapter i(introduction to java)Chapter i(introduction to java)
Chapter i(introduction to java)
 
Java 8 Stream API. A different way to process collections.
Java 8 Stream API. A different way to process collections.Java 8 Stream API. A different way to process collections.
Java 8 Stream API. A different way to process collections.
 
Scala - where objects and functions meet
Scala - where objects and functions meetScala - where objects and functions meet
Scala - where objects and functions meet
 
Operator overloading (binary)
Operator overloading (binary)Operator overloading (binary)
Operator overloading (binary)
 
Java Foundations: Maps, Lambda and Stream API
Java Foundations: Maps, Lambda and Stream APIJava Foundations: Maps, Lambda and Stream API
Java Foundations: Maps, Lambda and Stream API
 
Arrry structure Stacks in data structure
Arrry structure Stacks  in data structureArrry structure Stacks  in data structure
Arrry structure Stacks in data structure
 

Similaire à Here are the steps to get the closest airports to a named airport using the Freebase data and functions defined:1. Get all airports from Freebase with locations:let allAirports = GetAllAirports 1002. Pass the airport name and list of all airports to GetAirportsNear:GetAirportsNear "Heathrow" allAirportsThis will find the airport named "Heathrow" in the list, then call GetClosest to get the 20 closest airports based on great circle distance. It prints out the name and distance of each close airport

How to become an Android dev starting from iOS (and vice versa)
How to become an Android dev starting from iOS (and vice versa)How to become an Android dev starting from iOS (and vice versa)
How to become an Android dev starting from iOS (and vice versa)Giuseppe Filograno
 
Lecture#6 functions in c++
Lecture#6 functions in c++Lecture#6 functions in c++
Lecture#6 functions in c++NUST Stuff
 
Go Programming Language (Golang)
Go Programming Language (Golang)Go Programming Language (Golang)
Go Programming Language (Golang)Ishin Vin
 
How to add an optimization for C# to RyuJIT
How to add an optimization for C# to RyuJITHow to add an optimization for C# to RyuJIT
How to add an optimization for C# to RyuJITEgor Bogatov
 
FS2 for Fun and Profit
FS2 for Fun and ProfitFS2 for Fun and Profit
FS2 for Fun and ProfitAdil Akhter
 
TI1220 Lecture 6: First-class Functions
TI1220 Lecture 6: First-class FunctionsTI1220 Lecture 6: First-class Functions
TI1220 Lecture 6: First-class FunctionsEelco Visser
 
От Java Threads к лямбдам, Андрей Родионов
От Java Threads к лямбдам, Андрей РодионовОт Java Threads к лямбдам, Андрей Родионов
От Java Threads к лямбдам, Андрей РодионовYandex
 
From Java to Scala - advantages and possible risks
From Java to Scala - advantages and possible risksFrom Java to Scala - advantages and possible risks
From Java to Scala - advantages and possible risksSeniorDevOnly
 
From object oriented to functional domain modeling
From object oriented to functional domain modelingFrom object oriented to functional domain modeling
From object oriented to functional domain modelingCodemotion
 
Using-Python-Libraries.9485146.powerpoint.pptx
Using-Python-Libraries.9485146.powerpoint.pptxUsing-Python-Libraries.9485146.powerpoint.pptx
Using-Python-Libraries.9485146.powerpoint.pptxUadAccount
 
From object oriented to functional domain modeling
From object oriented to functional domain modelingFrom object oriented to functional domain modeling
From object oriented to functional domain modelingMario Fusco
 
Java/Scala Lab: Анатолий Кметюк - Scala SubScript: Алгебра для реактивного пр...
Java/Scala Lab: Анатолий Кметюк - Scala SubScript: Алгебра для реактивного пр...Java/Scala Lab: Анатолий Кметюк - Scala SubScript: Алгебра для реактивного пр...
Java/Scala Lab: Анатолий Кметюк - Scala SubScript: Алгебра для реактивного пр...GeeksLab Odessa
 
Programming Sideways: Asynchronous Techniques for Android
Programming Sideways: Asynchronous Techniques for AndroidProgramming Sideways: Asynchronous Techniques for Android
Programming Sideways: Asynchronous Techniques for AndroidEmanuele Di Saverio
 
Threads, Queues, and More: Async Programming in iOS
Threads, Queues, and More: Async Programming in iOSThreads, Queues, and More: Async Programming in iOS
Threads, Queues, and More: Async Programming in iOSTechWell
 
Monadologie
MonadologieMonadologie
Monadologieleague
 
What can be done with Java, but should better be done with Erlang (@pavlobaron)
What can be done with Java, but should better be done with Erlang (@pavlobaron)What can be done with Java, but should better be done with Erlang (@pavlobaron)
What can be done with Java, but should better be done with Erlang (@pavlobaron)Pavlo Baron
 

Similaire à Here are the steps to get the closest airports to a named airport using the Freebase data and functions defined:1. Get all airports from Freebase with locations:let allAirports = GetAllAirports 1002. Pass the airport name and list of all airports to GetAirportsNear:GetAirportsNear "Heathrow" allAirportsThis will find the airport named "Heathrow" in the list, then call GetClosest to get the 20 closest airports based on great circle distance. It prints out the name and distance of each close airport (20)

Monads in Swift
Monads in SwiftMonads in Swift
Monads in Swift
 
How to become an Android dev starting from iOS (and vice versa)
How to become an Android dev starting from iOS (and vice versa)How to become an Android dev starting from iOS (and vice versa)
How to become an Android dev starting from iOS (and vice versa)
 
Lecture#6 functions in c++
Lecture#6 functions in c++Lecture#6 functions in c++
Lecture#6 functions in c++
 
Go Programming Language (Golang)
Go Programming Language (Golang)Go Programming Language (Golang)
Go Programming Language (Golang)
 
How to add an optimization for C# to RyuJIT
How to add an optimization for C# to RyuJITHow to add an optimization for C# to RyuJIT
How to add an optimization for C# to RyuJIT
 
FS2 for Fun and Profit
FS2 for Fun and ProfitFS2 for Fun and Profit
FS2 for Fun and Profit
 
TI1220 Lecture 6: First-class Functions
TI1220 Lecture 6: First-class FunctionsTI1220 Lecture 6: First-class Functions
TI1220 Lecture 6: First-class Functions
 
От Java Threads к лямбдам, Андрей Родионов
От Java Threads к лямбдам, Андрей РодионовОт Java Threads к лямбдам, Андрей Родионов
От Java Threads к лямбдам, Андрей Родионов
 
From Java to Scala - advantages and possible risks
From Java to Scala - advantages and possible risksFrom Java to Scala - advantages and possible risks
From Java to Scala - advantages and possible risks
 
From object oriented to functional domain modeling
From object oriented to functional domain modelingFrom object oriented to functional domain modeling
From object oriented to functional domain modeling
 
Using-Python-Libraries.9485146.powerpoint.pptx
Using-Python-Libraries.9485146.powerpoint.pptxUsing-Python-Libraries.9485146.powerpoint.pptx
Using-Python-Libraries.9485146.powerpoint.pptx
 
From object oriented to functional domain modeling
From object oriented to functional domain modelingFrom object oriented to functional domain modeling
From object oriented to functional domain modeling
 
Java/Scala Lab: Анатолий Кметюк - Scala SubScript: Алгебра для реактивного пр...
Java/Scala Lab: Анатолий Кметюк - Scala SubScript: Алгебра для реактивного пр...Java/Scala Lab: Анатолий Кметюк - Scala SubScript: Алгебра для реактивного пр...
Java/Scala Lab: Анатолий Кметюк - Scala SubScript: Алгебра для реактивного пр...
 
operator overloading
operator overloadingoperator overloading
operator overloading
 
functions
functionsfunctions
functions
 
Programming Sideways: Asynchronous Techniques for Android
Programming Sideways: Asynchronous Techniques for AndroidProgramming Sideways: Asynchronous Techniques for Android
Programming Sideways: Asynchronous Techniques for Android
 
Threads, Queues, and More: Async Programming in iOS
Threads, Queues, and More: Async Programming in iOSThreads, Queues, and More: Async Programming in iOS
Threads, Queues, and More: Async Programming in iOS
 
Monadologie
MonadologieMonadologie
Monadologie
 
Hadoop + Clojure
Hadoop + ClojureHadoop + Clojure
Hadoop + Clojure
 
What can be done with Java, but should better be done with Erlang (@pavlobaron)
What can be done with Java, but should better be done with Erlang (@pavlobaron)What can be done with Java, but should better be done with Erlang (@pavlobaron)
What can be done with Java, but should better be done with Erlang (@pavlobaron)
 

Dernier

Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024The Digital Insurer
 
Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...Enterprise Knowledge
 
Scaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationScaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationRadu Cotescu
 
Slack Application Development 101 Slides
Slack Application Development 101 SlidesSlack Application Development 101 Slides
Slack Application Development 101 Slidespraypatel2
 
2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...Martijn de Jong
 
A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)Gabriella Davis
 
Artificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsArtificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsJoaquim Jorge
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerThousandEyes
 
IAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsIAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsEnterprise Knowledge
 
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...Igalia
 
Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024The Digital Insurer
 
CNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of ServiceCNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of Servicegiselly40
 
Exploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone ProcessorsExploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone Processorsdebabhi2
 
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...Neo4j
 
[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdfhans926745
 
Histor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slideHistor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slidevu2urc
 
How to convert PDF to text with Nanonets
How to convert PDF to text with NanonetsHow to convert PDF to text with Nanonets
How to convert PDF to text with Nanonetsnaman860154
 
Factors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptxFactors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptxKatpro Technologies
 
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...apidays
 
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking MenDelhi Call girls
 

Dernier (20)

Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024
 
Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...
 
Scaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationScaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organization
 
Slack Application Development 101 Slides
Slack Application Development 101 SlidesSlack Application Development 101 Slides
Slack Application Development 101 Slides
 
2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...
 
A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)
 
Artificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsArtificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and Myths
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected Worker
 
IAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsIAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI Solutions
 
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
 
Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024
 
CNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of ServiceCNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of Service
 
Exploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone ProcessorsExploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone Processors
 
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
 
[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf
 
Histor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slideHistor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slide
 
How to convert PDF to text with Nanonets
How to convert PDF to text with NanonetsHow to convert PDF to text with Nanonets
How to convert PDF to text with Nanonets
 
Factors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptxFactors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptx
 
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
 
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
 

Here are the steps to get the closest airports to a named airport using the Freebase data and functions defined:1. Get all airports from Freebase with locations:let allAirports = GetAllAirports 1002. Pass the airport name and list of all airports to GetAirportsNear:GetAirportsNear "Heathrow" allAirportsThis will find the airport named "Heathrow" in the list, then call GetClosest to get the 20 closest airports based on great circle distance. It prints out the name and distance of each close airport

  • 2. F# in a nutshell  Microsoft first class supported language for .NET  Supports OO and functional paradigms  Compiles to CLI like C#, VB.Net  First class citizen in VS2010 and VS2012 (free!). (Also in 2013 preview)  Open source, runs on Mono (use Xamarin)  Strongly typed
  • 3. F# functions  Use ‘let’ to declare functions and values let add x y = x + y  The return value of the function is the last value calculated (no ‘return’ statement let add x y = x + y  Types are inferred (at design time)  Argument lists don’t have brackets
  • 4. F# Interactive (FSI) > let add x y = x + y;; val add : x:int -> y:int -> int > add 3 4;; val it : int = 7 > • Use F# interactive to define and try out functions
  • 5. Calculating present value > let presentValue fv r t = fv * (1.+r) ** (-t);; val presentValue : fv:float -> r:float -> t:float -> float > presentValue 2000.0 0.07 10.;; val it : float = 1016.698584 > • Formulae can be represented very directly
  • 6. The ‘map’ function  Take some collection (array, list, IEnumerable)  For every value calculate and return some other value  Result is another array/list/IEnumerable containing the results let someSquares min max = // This generates an array from min to max: let numbers = [|min..max|] Array.map (fun x -> x * x) numbers val someSquares : min:int -> max:int -> int [] > someSquares 100 110;; val it : int [] = [|10000; 10201; 10404; 10609; 10816; 11025; 11236; 11449; 11664; 11881; 12100|] >
  • 7. The forward pipe operator |>  Takes the output from the preceding function  Places it into the (last) parameter of the following function let add x y = x + y let multiply x y = x * y val add : x:int -> y:int -> int val multiply : x:int -> y:int -> int > add 2 3 |> multiply 5;; val it : int = 25 >
  • 8. The forward pipe operator |> (2)  Comes into its own when dealing with collections let rootMeanSquare min max = [|min..max|] |> Array.map (fun x -> x * x) |> Array.average |> sqrt val rootMeanSquare : min:float -> max:float -> float > rootMeanSquare -10.0 10.0;; val it : float = 6.055300708 >
  • 9. The ‘mapi’ function  Like ‘map’ but provides you with an index value 0, 1, 2 etc. let someAdditions min max = [|min..max|] |> Array.mapi (fun i x -> i + x) val someAdditions : min:int -> max:int -> int [] > someAdditions 100 110;; val it : int [] = [|100; 102; 104; 106; 108; 110; 112; 114; 116; 118; 120|] >
  • 10. Calculating present value of a cashflow  Calculate the present value of a cashflow starting at time 0 let presentValue fv r t = fv * (1.+r) ** (-t) let cfPresentValue cf r = cf |> Array.mapi (fun t amt -> presentValue amt r (float(t))) |> Array.sum val presentValue : fv:float -> r:float -> t:float -> float val cfPresentValue : cf:float [] -> r:float -> float > cfPresentValue [|1000.0; 2000.0; 2500.0|] 0.07;; val it : float = 5052.755699 >
  • 12. Unit Testing and TDD  Create a new F# library project  Use Nuget to bring in FSUnit  Add GreatCircleTests.fs module GreatCircleTests open NUnit.Framework open FsUnit
  • 13. Write a trivial test! module GreatCircleTests open NUnit.Framework open FsUnit [<TestFixture>] type ``Given the GreatCircleDistance function``() = [<Test>] member x.``The function returns 0 for a journey between the same points``() = let expected = 0. let actual = GreatCircle.Distance 45. 50. 45. 50. actual |> should equal expected
  • 14. Pass the test! module GreatCircle let Distance lat1 long1 lat2 long2 = 0.
  • 15. What’s the next simplest test? [<Test>] member x.``The function returns 20014 km for a journey between the poles``() = let expected = 20014. let actual = GreatCircle.Distance -90. 0. 90. 0. actual |> should equal expected
  • 16. We’re gonna need an algorithm! var R = 6371; // km var dLat = (lat2-lat1).toRad(); var dLon = (lon2-lon1).toRad(); var lat1 = lat1.toRad(); var lat2 = lat2.toRad(); var a = Math.sin(dLat/2) * Math.sin(dLat/2) + Math.sin(dLon/2) * Math.sin(dLon/2) * Math.cos(lat1) * Math.cos(lat2); var c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1-a)); var d = R * c;
  • 17. How’s this? open System let Distance lat1 lon1 lat2 lon2 = let EarthRadius = 6378.1 let Deg2Rad deg = deg * Math.PI / 180. let lat1r = lat1 |> Deg2Rad let lat2r = lat2 |> Deg2Rad let dLat = lat2 - lat1 |> Deg2Rad let dLon = lon2 - lon1 |> Deg2Rad let a = (sin(dLat/2.) ** 2.) + (sin(dLon/2.) ** 2.) * cos(lat1r) * cos(lat2r) let c = 2. * atan2 (sqrt(a)) (sqrt(1.-a)) c * EarthRadius
  • 18. Whuuuuuuuuuuuuuuuuuu? ------ Test started: Assembly: FSUnitTestingExample.dll ------ Test 'GreatCircleTests+Given the GreatCircleDistance function.The function returns 20014 km for a journey between the poles' failed: Expected: 20014.0d But was: 20037.392103861061d at FsUnit.TopLevelOperators.should[a,a](FSharpFunc`2 f, a x, Object y) C:CodeVS2012FSUnitTestingExampleFSUnitTestingExampleGre atCircleTests.fs(28,0): at GreatCircleTests.Given the GreatCircleDistance function.The function returns 20014 km for a journey between the poles() 1 passed, 1 failed, 0 skipped, took 0.37 seconds (NUnit 2.6.1).
  • 19. They all laughed at Christopher Columbus… [<TestFixture>] type ``Given the GreatCircleDistance function``() = let margin = 0.003 [<Test>] member x.``The function returns 0 for a journey between the same points``() = let expected = 0. let actual = GreatCircle.Distance 45. 50. 45. 50. actual |> should (equalWithin margin) expected [<Test>] member x.``The function returns 20014 km for a journey between the poles``() = let expected = 20014. let actual = GreatCircle.Distance -90. 0. 90. 0. let error = expected * margin actual |> should (equalWithin error) expected
  • 20. Further tests better added as cases // Travel no distance: [<TestCase(0., 0., 0., 0., 0.)>] // Travel along the equator eastwards for 90 degrees: [<TestCase(0., 0., 0., 90., 10018.79)>] // Travel along the equator westwards for 90 degrees: [<TestCase(0., 0., 0., -90., 10018.79)>] // Travel along the equator eastwards for 180 degrees: [<TestCase(0., 0., 0., 180., 20037.58)>] // Travel along the equator westwards for 180 degrees: [<TestCase(0., 0., 0., -180., 20037.58)>] // Travel along the meridian northwards 90 degrees: [<TestCase(0., 0., 90., 0., 10018.79)>] // Travel along the meridian soutwards 90 degrees: [<TestCase(0., 0., -90., 0., 10018.79)>] // Travel from Farnham to Reigate: [<TestCase(51.214, -0.799, 51.230, -0.188, 42.6)>] // Travel from London to Sidney Australia: [<TestCase(51.51, -0.13, -33.86, 151.21, 16998.)>] member t.``the function returns the right result``(lat1, long1, lat2, long2, expected) = let actual = GreatCircle.Distance lat1 long1 lat2 long2 let error = expected * margin actual |> should (equalWithin error) expected
  • 21. Information-Rich Programming  Bring large, structured data sources into the code in a type-safe way… with Intellisense!  Implemented by ‘Type Providers’  Introduced with F#3.0 (VS2012)  Code-gen free!
  • 25. Get airports and locations /// Gets airports between a specified start and end index (to facilitate paged access). let GetAirportsPaged startIndex pageSize = query { for airport in dc.Transportation.Aviation.Airports do where ( airport.Geolocation <> null && airport.Geolocation.Latitude.HasValue && airport.Geolocation.Longitude.HasValue ) skip startIndex take pageSize select (airport.Name, airport.Geolocation.Latitude.Value, airport.Geolocation.Longitude.Value) } |> Array.ofSeq |> Array.map (fun (name, lat, long) -> { Name = name; Lat = lat; Long = long })
  • 26. Get airports and locations (2) /// Gets all airports from Freebase which have a defined location. let GetAllAirports pageSize = let rec getPage startIndex acc = let page = GetAirportsPaged startIndex pageSize if page.Length > 0 then Array.append acc (getPage (startIndex+pageSize) page) else acc getPage 0 [||]
  • 27. Get closest airports /// Gets the closest n airports to the given airport. let GetClosest target count airportList = airportList |> Array.map (fun airport -> airport, (DistanceBetween (airport.Lat) (airport.Long) (target.Lat) (target.Long))) |> Array.sortBy (fun (airport, distance) -> distance) |> Seq.truncate count |> Array.ofSeq
  • 28. Get closest airports to a named airport /// Gets airports near an airport specified by name. let GetAirportsNear name airportList = let target = airportList |> Array.tryFind (fun airport -> airport.Name.Contains(name)) if target.IsSome then airportList |> GetClosest target.Value 20 |> Array.iter (fun (airport, distance) -> printfn "%s - %f km" airport.Name distance) else printfn "Could not find %s" name