F# for Functional Enthusiasts
Jack Fox
jackfoxy.com  craftyThoughts
@foxyjackfox
Bibliography
jackfoxy.com/Fsharp_functio...
Type Providers
Microsoft.FSharp.Data.TypeProviders
DbmlFile
EdmxFile
ODataService
SqlDataConnection
SqlEntityConnection
Ws...
strongly typed ≠ object oriented
Typed Clojure project on indiegogo.com
Parameterized Polymorphism
a.k.a. Generics
let inline unsigned bitSize (zero : 'a) (one : 'a) =
let one' = one + zero
let ...
// Base Type Constraint
type Class1<'T when 'T :> System.Exception> …
// Interface Type Constraint
type Class2<'T when 'T ...
[<Measure>] type m // Distance, meters.
[<Measure>] type mile // Distance, miles.
[<Measure>] type s // Time, seconds.
[<M...
So far…
Type Providers: strongly typed external data
Strong typing and type inference
Type constraints
Units of Measur...
Vector
Eager Rose Tree
Vector
54321
Construct
Deconstruct
Initia
l
Las
t
[ ]
empt
y
;
;
type JsonValue =
| String of string
| Number of decimal
| Float of float
| Object of Map<string, JsonValue>
| Array of Jso...
JSON Parsing
Demo Crock Solution
FSI (REPL) compiles to assembly and executes
F# scripts
Fseye
Triple quoting
Red Black Tree Balancing
Source: https://wiki.rice.edu/confluence/download/attachments/2761212/Okasaki-Red-Black.pdf
a b
c...
Talk about reducing complexity!
type 'a t = Node of color * 'a * 'a t * 'a t | Leaf
let balance = function
| Black, z, Nod...
Computational Expressions
One syntactic sugar to rule them all
( monad, monoid, applicative functor )
seq {for n in 1..10 ...
Computational Expressions
Recursive Generators
let rec listFiles dir = seq {
yield! Directory.GetFiles(dir)
for subdir in ...
Computational Expressions
Query Expressions
let htmlPage =
query { for content in db.tbContentLib do
where (content.compan...
Computational Expressions
Query Expressions (Freebase)
let topBooksWithNameContaining (s:string) =
query { for book in
dat...
Async
let someBinding =
async {
let! x = … // asynchronous binding
let y = … // synchronous binding
let! z = … // another ...
Agents
a.k.a. Mailbox Processor
Message passing
Actor Model
Erlang-like processing
{m}brace
Cloud Computing (beta)
[<Cloud>]
let calculatePi (iterations : bigint) (digits : int) : ICloud<string> =
cloud {
...
Quotations
let ``Vector<Vector<'T>>, windowSeq``() =
test<@ [0; 1; 2; 3; 4; 5; 6; 7; 8; 9; 10;] =
([0; 1; 2; 3; 4; 5; 6; 7...
Now we’ve seen…
ML-style pattern matching
Syntactic sugar over common FP abstractions
Async and friends
Quotations
Nex...
Fsharp.org
F# Foundation
Owns resources relating to F# including:
the domain fsharp.org
the github.com/fsharp community or...
FAKE
 DSL implementation of build automation system
 Full use of F# language
 Access to any and all libraries
 Develop...
Literate Programming
FSharp.Formatting
Funscript
Javascript and Single Page Apps
JQuery and Javascript DOM APIs
TypeScript TypeProvider
Mini Web Server
Websharper
Fully composeable client-server web development.
#websharper on irc.freenode.net
GPU Process
Alea.cuBase
Complete commercial solution to develop highly optimized
CUDA accelerated GPU applications from F#...
Testing Options
FsUnit – native F# functional syntax across test tools
FsCheck – QuickCheck for F#
TickSpec – lightweight,...
Development Alternatives
Tsunami IDE (beta)
Visual Studio 2010, 2012, 2013 (free Express edition)
Xamarin Studio -- iOS, A...
IKVM lets Java and .NET Get Along!
Java from .NET, .NET from Java
JVM bytecode  IL instruction  native JIT
(not a bunc...
Questions?
F# Programming
http://en.wikibooks.org/wiki/F_Sharp_Programming
A Course of F# Study
http://jackfoxy.com/a-co...
Upcoming SlideShare
Loading in...5
×

F# for functional enthusiasts

1,239

Published on

Slides for my talk to the Bay Area Clojure User Group. Unlike most "entry level" F# talks, this presentation assumes some familiarity with functional programming concepts, although I think even folks unfamiliar with functional programming will find the content and demonstrations interesting. The talk includes a survey of the state of the F# community and community-driven (open source) projects.

Published in: Technology
0 Comments
4 Likes
Statistics
Notes
  • Be the first to comment

No Downloads
Views
Total Views
1,239
On Slideshare
0
From Embeds
0
Number of Embeds
1
Actions
Shares
0
Downloads
16
Comments
0
Likes
4
Embeds 0
No embeds

No notes for slide
  • Bibliograhy and sandbox projects of all sample code.multi-paradigm language
  • Strongly type external data or computing resources dynamicallyDemo freebase type providerDemo R type provider
  • Let&apos;s take the example of a Multiway Tree. Many kinds of documents can assume this form, HTML, XML, JSON docs, for example. We could model the sequences represented here with any linear data structure. Let&apos;s say it&apos;s Vector for arguments sake, and let&apos;s say the task at hand is to do a breadth first traversal.
  • Enter the Vector. Indexed lookup and update are pretty close to constant time, O(log32n) if you are keeping score, construction and deconstruction at the end of the sequence, more in line with how humans normally think of extending a linear sequence. You would probably construct days of observed weather this way, for instance.Steffen Forkmann’s implementation of Vector from Clojure. It implements a hash array mapped trie internally. It’s very fast, gives you essentially all the functionality of F# Array, with the added qualities of persistence and the ability to grow and shrink efficiently at the end of the sequence. Vector is probably the most versatile and performant purely functional structure for covering most of your needs involving eager evaluation since it includes indexed lookup and update.
  • Demo in CrockSolution w/ FsEye parsing into an eager rose tree
  • Demo in CrockSolution w/ FsEye parsing into an eager rose tree
  • …and that last line is just to prevent a compiler warning.
  • Monad Laws:Left identity:return a &gt;&gt;= f≡f aRight identity:m&gt;&gt;=return≡mAssociativity:(m &gt;&gt;= f)&gt;&gt;= g≡m &gt;&gt;=(\x -&gt; f x &gt;&gt;= g)Monoid Laws:Closure: Associativity: mappend x (mappend y z)=mappend(mappend x y) zIdentity element: mappendmempty x = x mappend x mempty= xevery monad is an applicative functor, but not conversely
  • The rec keyword is not required to be tail recursiveGetFiles returns a string[], so bang(!) required yield the entire enumerable
  • Inverted SQL style from LINQ“content.templateID.Value” because external data is poorly typed (it includes nulls) so it is returned as an Option type
  • Inverted SQL style from LINQ“content.templateID.Value” because external data is poorly typed (it includes nulls) so it is returned as an Option type
  • Demo in CrockSolution w/ FsEye
  • Unquote in TestSandbox
  • Demo in CrockSolution w/ FsEye
  • [Charting World Bank data with F#](http://funscript.info/live/worldbank.html)
  • http://fssnip.net/jQ
  • Java lib or app you want to use in a .NET app?.NET dll or app you want to use in the JVM?
  • F# for functional enthusiasts

    1. 1. F# for Functional Enthusiasts Jack Fox jackfoxy.com  craftyThoughts @foxyjackfox Bibliography jackfoxy.com/Fsharp_functional_enthusiasts_bibliography Sample Code https://gist.github.com/jackfoxy/6679238 https://github.com/jackfoxy/CrockSolution https://github.com/jackfoxy/TestSandbox 2012 annular eclipse observed by the author from Sugarloaf Peak, Lake Shasta
    2. 2. Type Providers Microsoft.FSharp.Data.TypeProviders DbmlFile EdmxFile ODataService SqlDataConnection SqlEntityConnection WsdlService Fsharpx AppSettings Excel Graph Machine Management Math Regex Xaml Xrm FSharp.Data Apiary Csv Freebase Json WorldBank Xml F# 3.0 Sample Pack DGML Word Csv DataStore Hadoop/Hive/Hdfs HelloWorld Management MiniCvs Xrm Tsunami RSS Reader Start Menu NuGetTypeProvider * S3TypeProvider * FacebookTypeProvider * DocumentTypeProvider * * (samples inside Tsunami) in the wild on Github FunScript R Matlab IKVM (Java) Python PowerShell
    3. 3. strongly typed ≠ object oriented Typed Clojure project on indiegogo.com
    4. 4. Parameterized Polymorphism a.k.a. Generics let inline unsigned bitSize (zero : 'a) (one : 'a) = let one' = one + zero let x' = one <<< (bitSize - 1) x' ||| one' bitSize:int -> zero: ^a -> one: ^a -> ^a when ^a : (static member ( + ) : ^a * ^a -> ^a) and ^a : (static member ( <<< ) : ^a * int32 -> ^a) and ^a : (static member ( ||| ) : ^a * ^a -> ^a)
    5. 5. // Base Type Constraint type Class1<'T when 'T :> System.Exception> … // Interface Type Constraint type Class2<'T when 'T :> System.IComparable> … // Comparison constraint type Class10<'T when 'T : comparison> … // Member constraint with property type Class6<'T when 'T : (member Property1 : int)> … Constraints on Type Definitions
    6. 6. [<Measure>] type m // Distance, meters. [<Measure>] type mile // Distance, miles. [<Measure>] type s // Time, seconds. [<Measure>] type h // Time, hours. let distance1 = 100.0<m> let distance2 = 250.0<mile> let speedMetersPerSec = distance1 / 10.0<s> // float<m/s> let speedMPH = distance2 / 5.0<h> // float<mile/h> let x = distance1 + distance2 //will not compile Units of Measure Design Time Type Checking
    7. 7. So far… Type Providers: strongly typed external data Strong typing and type inference Type constraints Units of Measure Next up… Nuts and bolts programming
    8. 8. Vector Eager Rose Tree
    9. 9. Vector 54321 Construct Deconstruct Initia l Las t [ ] empt y ; ;
    10. 10. type JsonValue = | String of string | Number of decimal | Float of float | Object of Map<string, JsonValue> | Array of JsonValue[] | Boolean of bool | Null JSON Parsing Discriminated Union Type from FSharp.Data
    11. 11. JSON Parsing Demo Crock Solution FSI (REPL) compiles to assembly and executes F# scripts Fseye Triple quoting
    12. 12. Red Black Tree Balancing Source: https://wiki.rice.edu/confluence/download/attachments/2761212/Okasaki-Red-Black.pdf a b c d b ca d a a b c d b c d a c b d
    13. 13. Talk about reducing complexity! type 'a t = Node of color * 'a * 'a t * 'a t | Leaf let balance = function | Black, z, Node (Red, y, Node (Red, x, a, b), c), d | Black, z, Node (Red, x, a, Node (Red, y, b, c)), d | Black, x, a, Node (Red, z, Node (Red, y, b, c), d) | Black, x, a, Node (Red, y, b, Node (Red, z, c, d)) -> Node (Red, y, Node (Black, x, a, b), Node (Black, z, c, d)) | x -> Node x Source: http://fsharpnews.blogspot.com/2010/07/f-vs-mathematica-red-black- trees.html
    14. 14. Computational Expressions One syntactic sugar to rule them all ( monad, monoid, applicative functor ) seq {for n in 1..10 do yield n yield n * 2} seq {for n in 1..10 do yield (n, n * 2)} Sequence Generators
    15. 15. Computational Expressions Recursive Generators let rec listFiles dir = seq { yield! Directory.GetFiles(dir) for subdir in Directory.GetDirectories(dir) do yield! listFiles subdir } let musicFiles = listFiles "E:music" |> List.ofSeq
    16. 16. Computational Expressions Query Expressions let htmlPage = query { for content in db.tbContentLib do where (content.companyID.Value > 0 and content.isHtml) join template in db.tbTemplate on (content.templateID.Value = template.templateID) select (content.styleID, template.title, template.body) }
    17. 17. Computational Expressions Query Expressions (Freebase) let topBooksWithNameContaining (s:string) = query { for book in data.``Arts and Entertainment``.Books.Books do where (book.Name.ApproximatelyMatches s) take 10 select book.Name }
    18. 18. Async let someBinding = async { let! x = … // asynchronous binding let y = … // synchronous binding let! z = … // another asynchronous binding do! … // asynchronous execution return z // return something (or not) }
    19. 19. Agents a.k.a. Mailbox Processor Message passing Actor Model Erlang-like processing
    20. 20. {m}brace Cloud Computing (beta) [<Cloud>] let calculatePi (iterations : bigint) (digits : int) : ICloud<string> = cloud { let! workers = Cloud.GetWorkerCount() let workers = bigint (2 * workers) ... let runWorker iterations = cloud { return monteCarloPiWorker iterations } let! results = ... |> Cloud.Parallel ... return getDigits a b |> ... }
    21. 21. Quotations let ``Vector<Vector<'T>>, windowSeq``() = test<@ [0; 1; 2; 3; 4; 5; 6; 7; 8; 9; 10;] = ([0; 1; 2; 3; 4; 5; 6; 7; 8; 9; ] |> Vector.windowSeq 3 |> Vector.flatten |> List.ofSeq) @>
    22. 22. Now we’ve seen… ML-style pattern matching Syntactic sugar over common FP abstractions Async and friends Quotations Next: Community-Driven Development Fsharp.org Some “core” projects Dev environments
    23. 23. Fsharp.org F# Foundation Owns resources relating to F# including: the domain fsharp.org the github.com/fsharp community organization the fsharporg twitter account Seeks to: promote the adoption of F# expand the relevance and importance of F# skills and knowledge expand the range of technologies which can interoperate with F# expand the range of platforms where F# can be used facilitate the ongoing development of F#-related technology and resources
    24. 24. FAKE  DSL implementation of build automation system  Full use of F# language  Access to any and all libraries  Develop with powerful debuggers and IDEs
    25. 25. Literate Programming FSharp.Formatting
    26. 26. Funscript Javascript and Single Page Apps JQuery and Javascript DOM APIs TypeScript TypeProvider Mini Web Server
    27. 27. Websharper Fully composeable client-server web development. #websharper on irc.freenode.net
    28. 28. GPU Process Alea.cuBase Complete commercial solution to develop highly optimized CUDA accelerated GPU applications from F# quotations by QuantAlea. Advantages of functional composition and rapid prototyping Don’t have a NVIDIA card? Try Brahma.Fsharp F# quotations to OpenCL translation
    29. 29. Testing Options FsUnit – native F# functional syntax across test tools FsCheck – QuickCheck for F# TickSpec – lightweight, but fully featured Gherkin BDD Canopy – lightweight F# syntax for web-client Selenium testing Unquote – step-by-step F# expression evaluations
    30. 30. Development Alternatives Tsunami IDE (beta) Visual Studio 2010, 2012, 2013 (free Express edition) Xamarin Studio -- iOS, Android, Mac, Mono, .NET (free edition limits project size) Emacs Vim SublimeText
    31. 31. IKVM lets Java and .NET Get Along! Java from .NET, .NET from Java JVM bytecode  IL instruction  native JIT (not a bunch of wrappers) 10+ years of development effort Actively supported Powers Mono Extremely few edge incompatibilities
    32. 32. Questions? F# Programming http://en.wikibooks.org/wiki/F_Sharp_Programming A Course of F# Study http://jackfoxy.com/a-course-of-fsharp-study A directory of useful pages http://fsharpforfunandprofit.com/site-contents Learning F#
    1. A particular slide catching your eye?

      Clipping is a handy way to collect important slides you want to go back to later.

    ×