SlideShare a Scribd company logo
1 of 33
Download to read offline
FunScript
 Zach Bray 2013
Me

           • Energy trading systems
           • C#/F#/C++
           • Functional
                           zbray.com
                            @zbray

* Lots of F#
* Calculation Engine
* Not a JS expert
What is FunScript?

              // F# Code -> JavaScript Code
              Compiler.Compile: Expr -> string




* F# Code -> JS Code
* Quotation Expr -> String
* Quotations in F# provide a way of getting the AST from a piece of code.
What does it support?

          • Most F# code
          • A little mscorlib
          • 400+ bootstrapped tests


* Bootstrapped: FSharp.PowerPack + JInt
Primitives

           • Strings
           • Numbers (beware!)
           • Booleans


* Ints/Bytes/etc. all converted to number.
* Loops that look infinite can turn out to be finite...
Flow
                                                            var _temp1;
                                                            if (x)
              let y =                                       {
                                                               _temp1 = "foo";
                if x then "foo"                             }
                                                            else
                else "bar"                                  {
                                                               _temp1 = "bar";
              y                                             };
                                                            var y = _temp1;
                                                            return y;


                                                            var xs = List_CreateCons(1.000000,
                                                            List_CreateCons(2.000000,
                                                            List_CreateCons(3.000000,
                                                            List_Empty())));
          let xs = [1; 2; 3]                                if ((xs.Tag == "Cons"))
                                                            {
          match xs with                                       var _xs = List_Tail(xs);
                                                              var x = List_Head(xs);
          | x::xs -> x                                        return x;
                                                            }
          | _ -> failwith "never"                           else
                                                            {
                                                              throw ("never");
                                                            }




*   Inline if... then... else... blocks
*   Pattern matching
*   While + For loops
*   Caveat: Quotation Problem: “for x in xs” when xs is an array
Functions
                                                  var isOdd = (function (x)

       let isOdd x = x % 2 <> 0                   {
                                                    return ((x % 2.000000).CompareTo(0.000000) != 0.000000);

       isOdd 2                                    });
                                                  return isOdd(2.000000);




                                                return (function (x)
                                                {
       (fun x -> x % 2 = 0)(2)                      return ((x % 2.000000).CompareTo(0.000000) == 0.000000);
                                                })(2.000000);




* Let bound functions
* Anonymous lambda functions
* Note/Caveat: CompareTo rather than operators: Allows structural equality. Has negative
impact on performance. Cite: Mandelbrot test by Carsten Koenig 100x worse than JS vs.
1000x for Fay.
Records
        type Person =                                     var i_Person__ctor;
                                                          i_Person__ctor = (function (Name, Age)
          { Name: string; Age: int }                      {
                                                            this.Name = Name;
        let bob =                                           this.Age = Age;
                                                          });
          { Name = "Bob"; Age = 25 }                      var bob = (new i_Person__ctor("Bob", 25.000000));




                                                          var now = (new i_Person__ctor("Bob", 25.000000));
    let now = { Name = "Bob"; Age = 25 }                  var _temp1;
                                                          var Age = 26.000000;
    let soon = { now with Age = 26 }                      _temp1 = (new i_Person__ctor(now.Name, Age));
                                                          var soon = _temp1;




        ...but also discriminated unions, classes and modules


*   Most of the types you can define
*   Records, DUs, Classes, Modules
*   Records very similar to JSON.
*   Record expressions are shallow copies with some changes
*   Records & DUs have structural equality.
*   Caveat: Class inheritance doesn’t work (yet)
*   Caveat: DU structural equality is broken on the main branch.
Operators
        let xs = [10 .. 20]                            var xs = Seq_ToList(Range_oneStep(10.000000, 20.000000));




     let xs = [10 .. 2 .. 20]                    var xs = Seq_ToList(Range_customStep(10.000000, 2.000000, 20.000000));




                                                                        var incr = (function (x)
         let incr x = x + 1                                             {
                                                                          return (x + 1.000000);
         let x = 10                                                     });
                                                                        var x = 10.000000;
         x |> incr                                                      return incr(x)




                                                                       var incr = (function (x)
                                                                       {
                                                                         return (x + 1.000000);
                                                                       });
       let incr x = x + 1.                                             var divBy2 = (function (x)
                                                                       {
       let divBy2 x = x / 2.                                             return (x / 2.000000);
                                                                       });
       (incr << divBy2) 10.                                            return (function (x)
                                                                       {
                                                                         return incr(divBy2(x));
                                                                       })(10.000000);




*   Logic & Arithmetic too (obviously)
*   But also... identity, ignore, defaultArg, reference assignment etc.
*   Can also define your own.
*   See the tests for a complete list.
Computation
                        expressions

                                                  return (function (arg00)
                                                  {
                                                    return Async_StartImmediate(arg00, {Tag: "None"});
                                                  })((function (builder_)
       async { return () }                        {
                                                    return builder_.Delay((function (unitVar)
       |> Async.StartImmediate                      {
                                                      var _temp3;
                                                      return builder_.Return(_temp3);
                                                    }));
                                                  })(Async_get_async()));




* Async workflow built in...
* Can define your own too, e.g., the maybe monad if you wanted it
* LiveScript has the concept of back calls
Data structures
• Array
• List
• Seq
• Map
• Set
• Option
Bored yet?




Boring bit over (hopefully).
We’re half way to the pub.
Why bother?
Enormous number of devices. More than .Net or Mono.
Not just for the browser.
* Desktop Apps.
* Tablet/Phone Apps.
* Servers.
Don’t we have this
                      already?
           • FSWebTools
           • WebSharper
           • Pit
           • JSIL

F# has a long history of compiling to JavaScript
Tomas released FSWebTools back in 2006 or 07.
CoffeeScript appeared in 2009.
But FunScript is focusing on something slightly different...
Extensibility




We cannot port the whole framework.
... but we can give you the tools to chip off the bits you need.
Movie data example




Tomas built this web app with FunScript.
No .NET the whole thing runs in JS.
* Who is familar with type providers?
* Like code gen, but without the manual step and can be lazy (which is great for stuff like
freebase)...
Mapping the Apiary.io
                    type provider
               • Makes calls to the framework
               • Not quotation friendly
               • We replace (or re-route) the calls to
                    quotation friendly methods and types
    ExpressionReplacer.createUnsafe <@ ApiaryDocument.Create @> <@ JsonProvider.JsRuntime.CreateDocument @>
    ExpressionReplacer.createUnsafe <@ fun (d:ApiaryDocument) -> d.JsonValue @> <@ JsonProvider.JsRuntime.Identity @>
    ExpressionReplacer.createUnsafe <@ fun (d:ApiaryDocument) -> d.Context @> <@ getContext @>




       Compiler.Compile(<@ page() @>, components=FunScript.Data.Components.DataProviders)




*   We cannot use the provider out of the box...
*   But because the compiler is EXTENSIBLE we can tell it how to convert those calls.
*   It [the compiler] will find all call sites and change them.
*   Then we can use the provider in our JavaScript output
*   Any questions on that?
* OK so...
* That’s one feature that existing implementations don’t have.
* What else?
What about these?




                                                                      Elm

                              See: http://altjs.org/
* Many languages target JavaScript now.
* It has become a kind of IL.
* Some are quite good. I recommend LiveScript if you don’t mind something dynamic.
Dynamically typed
             •   Good at interop

             •   But if its too close to
                 JavaScript...




*   Can reuse existing libraries
*   Can consume JS data
*   But...
*   Inconsistent operations (annoying on forms)
*   Dodgy for ... in ... loops, although fixed in most compile to JS languages
*   Dodgy function scope. Yuck!
*   Counter-intuitive “Falsey” values
*   Auto semi-colon insertion
Statically typed:
                          FFI sucks




*   Foreign function interface
*   Have to map every function you want to use
*   Tedious and error prone - may as well go dynamic
*   This is Fay. But same in Roy, js_of_ocaml, etc.
*   Can do this in FunScript too.
The Lonely Island




* If you have to use FFI you are a lonely island
* Cannot easily access any of the existing JavaScript infrastructure
Bypass FFI with type
                   providers




* Uses similar techniques to those I described in the Movie example
* The TypeScript library creates a bunch of types and tells the compiler how to turn them into
JavaScript.
* F# is the only language that supports this workflow at the moment!
Just the beginning

           • TypeScript only has mappings for 10s of
               JavaScript libraries.
           • Google Closure annotations
           • JavaScript type inferrer


* Google closure might provide many more mappings
* JavaScript type inferrer would probably be very hard to build but it would be awesome

- EDIT: Colin Bull has already made a little progress towards this: https://github.com/
colinbull/IronJS/commit/612b799351a37d720920d4c68797787d2b72aaca
- EDIT: We could even have a type provider to the node package manager (NPM) then we
wouldn’t even need to mess around with files. For example:

type npmProvider = NodePacakgeManager()
let npm = npmProvider.GetContext()
let express = npm.express.v3_1_2
let connect = npm.connect.v2_7_2
...
GitHub numbers


                                                                       •    JavaScript: #1


                                                                       •    FSharp: #43




                                                   Sources:
                                         www.github.com/languages/
                      www.r-chart.com/2010/08/github-stats-on-programming-languages.html
So this is the sell...
Why should you go out and build me a JavaScript type inferrer...
21% of the projects on GitHub are _labelled_ as JavaScript
2010-2012: http://t.arboreus.com/post/31469214663/visualizing-changes-in-popularity-rankings-of




* This is how the popularity of programming languages has changed (according to fairly
arbitrary measures) in the last two years.
* JavaScript is still on top.
LinkedIn numbers
 JavaScript                     F#


 914,000 people              2,000 people




                  in scale
Thanks to the
          FunScript contributors
           • Tomas Petricek
           • Phillip Trelford
           • James Freiwirth
           • Robert Pickering
           • Steffen Forkmann

If you’d like to contribute come and talk to me afterwards.
Summary

• FunScript compiles F# into JavaScript
• It is extensible: re-route any method call
• F# is the only statically typed language (that

           capable of taking advantage of
  I’m aware of)

  JavaScript libraries without FFI or code-gen
Questions?

More Related Content

What's hot

Useful functions for arrays in php
Useful functions for arrays in phpUseful functions for arrays in php
Useful functions for arrays in phpChetan Patel
 
The Ring programming language version 1.2 book - Part 20 of 84
The Ring programming language version 1.2 book - Part 20 of 84The Ring programming language version 1.2 book - Part 20 of 84
The Ring programming language version 1.2 book - Part 20 of 84Mahmoud Samir Fayed
 
Swift for TensorFlow - CoreML Personalization
Swift for TensorFlow - CoreML PersonalizationSwift for TensorFlow - CoreML Personalization
Swift for TensorFlow - CoreML PersonalizationJacopo Mangiavacchi
 
JDays Lviv 2014: Java8 vs Scala: Difference points & innovation stream
JDays Lviv 2014:  Java8 vs Scala:  Difference points & innovation streamJDays Lviv 2014:  Java8 vs Scala:  Difference points & innovation stream
JDays Lviv 2014: Java8 vs Scala: Difference points & innovation streamRuslan Shevchenko
 
Scala vs Java 8 in a Java 8 World
Scala vs Java 8 in a Java 8 WorldScala vs Java 8 in a Java 8 World
Scala vs Java 8 in a Java 8 WorldBTI360
 
oop presentation note
oop presentation note oop presentation note
oop presentation note Atit Patumvan
 
Haskell in the Real World
Haskell in the Real WorldHaskell in the Real World
Haskell in the Real Worldosfameron
 
Swift rocks! #1
Swift rocks! #1Swift rocks! #1
Swift rocks! #1Hackraft
 
Common derivatives integrals_reduced
Common derivatives integrals_reducedCommon derivatives integrals_reduced
Common derivatives integrals_reducedKyro Fitkry
 
Lesson 8: Basic Differentiation Rules
Lesson 8: Basic Differentiation RulesLesson 8: Basic Differentiation Rules
Lesson 8: Basic Differentiation RulesMatthew Leingang
 
The Ring programming language version 1.5.1 book - Part 29 of 180
The Ring programming language version 1.5.1 book - Part 29 of 180The Ring programming language version 1.5.1 book - Part 29 of 180
The Ring programming language version 1.5.1 book - Part 29 of 180Mahmoud Samir Fayed
 
The Macronomicon
The MacronomiconThe Macronomicon
The MacronomiconMike Fogus
 
Calculus Cheat Sheet All
Calculus Cheat Sheet AllCalculus Cheat Sheet All
Calculus Cheat Sheet AllMoe Han
 
Lesson 8: Basic Differentiation Rules
Lesson 8: Basic Differentiation RulesLesson 8: Basic Differentiation Rules
Lesson 8: Basic Differentiation RulesMatthew Leingang
 
Functional Object-Oriented Imperative Scala / 関数型オブジェクト指向命令型 Scala by Sébasti...
Functional Object-Oriented Imperative Scala / 関数型オブジェクト指向命令型 Scala by Sébasti...Functional Object-Oriented Imperative Scala / 関数型オブジェクト指向命令型 Scala by Sébasti...
Functional Object-Oriented Imperative Scala / 関数型オブジェクト指向命令型 Scala by Sébasti...scalaconfjp
 
Swift Rocks #2: Going functional
Swift Rocks #2: Going functionalSwift Rocks #2: Going functional
Swift Rocks #2: Going functionalHackraft
 
Calculus cheat sheet_integrals
Calculus cheat sheet_integralsCalculus cheat sheet_integrals
Calculus cheat sheet_integralsUrbanX4
 

What's hot (20)

Useful functions for arrays in php
Useful functions for arrays in phpUseful functions for arrays in php
Useful functions for arrays in php
 
SDC - Einführung in Scala
SDC - Einführung in ScalaSDC - Einführung in Scala
SDC - Einführung in Scala
 
The Ring programming language version 1.2 book - Part 20 of 84
The Ring programming language version 1.2 book - Part 20 of 84The Ring programming language version 1.2 book - Part 20 of 84
The Ring programming language version 1.2 book - Part 20 of 84
 
Swift for TensorFlow - CoreML Personalization
Swift for TensorFlow - CoreML PersonalizationSwift for TensorFlow - CoreML Personalization
Swift for TensorFlow - CoreML Personalization
 
JDays Lviv 2014: Java8 vs Scala: Difference points & innovation stream
JDays Lviv 2014:  Java8 vs Scala:  Difference points & innovation streamJDays Lviv 2014:  Java8 vs Scala:  Difference points & innovation stream
JDays Lviv 2014: Java8 vs Scala: Difference points & innovation stream
 
Scala vs Java 8 in a Java 8 World
Scala vs Java 8 in a Java 8 WorldScala vs Java 8 in a Java 8 World
Scala vs Java 8 in a Java 8 World
 
oop presentation note
oop presentation note oop presentation note
oop presentation note
 
Grammarware Memes
Grammarware MemesGrammarware Memes
Grammarware Memes
 
Haskell in the Real World
Haskell in the Real WorldHaskell in the Real World
Haskell in the Real World
 
Swift rocks! #1
Swift rocks! #1Swift rocks! #1
Swift rocks! #1
 
Common derivatives integrals_reduced
Common derivatives integrals_reducedCommon derivatives integrals_reduced
Common derivatives integrals_reduced
 
Lesson 8: Basic Differentiation Rules
Lesson 8: Basic Differentiation RulesLesson 8: Basic Differentiation Rules
Lesson 8: Basic Differentiation Rules
 
Java Cheat Sheet
Java Cheat SheetJava Cheat Sheet
Java Cheat Sheet
 
The Ring programming language version 1.5.1 book - Part 29 of 180
The Ring programming language version 1.5.1 book - Part 29 of 180The Ring programming language version 1.5.1 book - Part 29 of 180
The Ring programming language version 1.5.1 book - Part 29 of 180
 
The Macronomicon
The MacronomiconThe Macronomicon
The Macronomicon
 
Calculus Cheat Sheet All
Calculus Cheat Sheet AllCalculus Cheat Sheet All
Calculus Cheat Sheet All
 
Lesson 8: Basic Differentiation Rules
Lesson 8: Basic Differentiation RulesLesson 8: Basic Differentiation Rules
Lesson 8: Basic Differentiation Rules
 
Functional Object-Oriented Imperative Scala / 関数型オブジェクト指向命令型 Scala by Sébasti...
Functional Object-Oriented Imperative Scala / 関数型オブジェクト指向命令型 Scala by Sébasti...Functional Object-Oriented Imperative Scala / 関数型オブジェクト指向命令型 Scala by Sébasti...
Functional Object-Oriented Imperative Scala / 関数型オブジェクト指向命令型 Scala by Sébasti...
 
Swift Rocks #2: Going functional
Swift Rocks #2: Going functionalSwift Rocks #2: Going functional
Swift Rocks #2: Going functional
 
Calculus cheat sheet_integrals
Calculus cheat sheet_integralsCalculus cheat sheet_integrals
Calculus cheat sheet_integrals
 

Viewers also liked

dpi24/7, la plateforme de publication digitale pour les groupes de presse
dpi24/7, la plateforme de publication digitale pour les groupes de pressedpi24/7, la plateforme de publication digitale pour les groupes de presse
dpi24/7, la plateforme de publication digitale pour les groupes de presseAudaxis
 
JahiaOne 2015 - Belambra: the customer testomonial by Pierre Brahy and Pierre...
JahiaOne 2015 - Belambra: the customer testomonial by Pierre Brahy and Pierre...JahiaOne 2015 - Belambra: the customer testomonial by Pierre Brahy and Pierre...
JahiaOne 2015 - Belambra: the customer testomonial by Pierre Brahy and Pierre...Jahia Solutions Group
 
La centrale d'achat dédiée aux petites entreprises
La centrale d'achat dédiée aux petites entreprisesLa centrale d'achat dédiée aux petites entreprises
La centrale d'achat dédiée aux petites entreprisesCEFAC
 
PremiumPeers la plateforme collaborative de conseil en transformation
PremiumPeers la plateforme collaborative de conseil en transformationPremiumPeers la plateforme collaborative de conseil en transformation
PremiumPeers la plateforme collaborative de conseil en transformationComePinchart
 
My Web intelligence - Une plateforme open source au service des humanités dig...
My Web intelligence - Une plateforme open source au service des humanités dig...My Web intelligence - Une plateforme open source au service des humanités dig...
My Web intelligence - Une plateforme open source au service des humanités dig...Amar LAKEL, PhD
 
Fondamentaux du marketing digital
Fondamentaux du marketing digitalFondamentaux du marketing digital
Fondamentaux du marketing digitalTojuma consulting
 
Strategie de communication digitale Clarins
Strategie de communication digitale ClarinsStrategie de communication digitale Clarins
Strategie de communication digitale ClarinsSylvie Nourry
 
Domain Driven Design with the F# type System -- F#unctional Londoners 2014
Domain Driven Design with the F# type System -- F#unctional Londoners 2014Domain Driven Design with the F# type System -- F#unctional Londoners 2014
Domain Driven Design with the F# type System -- F#unctional Londoners 2014Scott Wlaschin
 

Viewers also liked (8)

dpi24/7, la plateforme de publication digitale pour les groupes de presse
dpi24/7, la plateforme de publication digitale pour les groupes de pressedpi24/7, la plateforme de publication digitale pour les groupes de presse
dpi24/7, la plateforme de publication digitale pour les groupes de presse
 
JahiaOne 2015 - Belambra: the customer testomonial by Pierre Brahy and Pierre...
JahiaOne 2015 - Belambra: the customer testomonial by Pierre Brahy and Pierre...JahiaOne 2015 - Belambra: the customer testomonial by Pierre Brahy and Pierre...
JahiaOne 2015 - Belambra: the customer testomonial by Pierre Brahy and Pierre...
 
La centrale d'achat dédiée aux petites entreprises
La centrale d'achat dédiée aux petites entreprisesLa centrale d'achat dédiée aux petites entreprises
La centrale d'achat dédiée aux petites entreprises
 
PremiumPeers la plateforme collaborative de conseil en transformation
PremiumPeers la plateforme collaborative de conseil en transformationPremiumPeers la plateforme collaborative de conseil en transformation
PremiumPeers la plateforme collaborative de conseil en transformation
 
My Web intelligence - Une plateforme open source au service des humanités dig...
My Web intelligence - Une plateforme open source au service des humanités dig...My Web intelligence - Une plateforme open source au service des humanités dig...
My Web intelligence - Une plateforme open source au service des humanités dig...
 
Fondamentaux du marketing digital
Fondamentaux du marketing digitalFondamentaux du marketing digital
Fondamentaux du marketing digital
 
Strategie de communication digitale Clarins
Strategie de communication digitale ClarinsStrategie de communication digitale Clarins
Strategie de communication digitale Clarins
 
Domain Driven Design with the F# type System -- F#unctional Londoners 2014
Domain Driven Design with the F# type System -- F#unctional Londoners 2014Domain Driven Design with the F# type System -- F#unctional Londoners 2014
Domain Driven Design with the F# type System -- F#unctional Londoners 2014
 

Similar to FunScript 2013 (with speakers notes)

Javascript Uncommon Programming
Javascript Uncommon ProgrammingJavascript Uncommon Programming
Javascript Uncommon Programmingjeffz
 
Building fast interpreters in Rust
Building fast interpreters in RustBuilding fast interpreters in Rust
Building fast interpreters in RustIngvar Stepanyan
 
Jscex: Write Sexy JavaScript
Jscex: Write Sexy JavaScriptJscex: Write Sexy JavaScript
Jscex: Write Sexy JavaScriptjeffz
 
Jscex: Write Sexy JavaScript (中文)
Jscex: Write Sexy JavaScript (中文)Jscex: Write Sexy JavaScript (中文)
Jscex: Write Sexy JavaScript (中文)jeffz
 
Lambda? You Keep Using that Letter
Lambda? You Keep Using that LetterLambda? You Keep Using that Letter
Lambda? You Keep Using that LetterKevlin Henney
 
深入浅出Jscex
深入浅出Jscex深入浅出Jscex
深入浅出Jscexjeffz
 
High Wizardry in the Land of Scala
High Wizardry in the Land of ScalaHigh Wizardry in the Land of Scala
High Wizardry in the Land of Scaladjspiewak
 
「Frama-Cによるソースコード検証」 (mzp)
「Frama-Cによるソースコード検証」 (mzp)「Frama-Cによるソースコード検証」 (mzp)
「Frama-Cによるソースコード検証」 (mzp)Hiroki Mizuno
 
Coffee Scriptでenchant.js
Coffee Scriptでenchant.jsCoffee Scriptでenchant.js
Coffee Scriptでenchant.jsNaoyuki Totani
 
Functional programming ii
Functional programming iiFunctional programming ii
Functional programming iiPrashant Kalkar
 
03. haskell refresher quiz
03. haskell refresher quiz03. haskell refresher quiz
03. haskell refresher quizSebastian Rettig
 
(How) can we benefit from adopting scala?
(How) can we benefit from adopting scala?(How) can we benefit from adopting scala?
(How) can we benefit from adopting scala?Tomasz Wrobel
 
Strinng Classes in c++
Strinng Classes in c++Strinng Classes in c++
Strinng Classes in c++Vikash Dhal
 
Principles of functional progrmming in scala
Principles of functional progrmming in scalaPrinciples of functional progrmming in scala
Principles of functional progrmming in scalaehsoon
 
TI1220 Lecture 6: First-class Functions
TI1220 Lecture 6: First-class FunctionsTI1220 Lecture 6: First-class Functions
TI1220 Lecture 6: First-class FunctionsEelco Visser
 
ภาษา C โปรแกรมย่อยและฟังก์ชันมาตรฐาน
ภาษา C โปรแกรมย่อยและฟังก์ชันมาตรฐานภาษา C โปรแกรมย่อยและฟังก์ชันมาตรฐาน
ภาษา C โปรแกรมย่อยและฟังก์ชันมาตรฐานNoppanon YourJust'one
 

Similar to FunScript 2013 (with speakers notes) (20)

Javascript Uncommon Programming
Javascript Uncommon ProgrammingJavascript Uncommon Programming
Javascript Uncommon Programming
 
Introducing scala
Introducing scalaIntroducing scala
Introducing scala
 
Scala Bootcamp 1
Scala Bootcamp 1Scala Bootcamp 1
Scala Bootcamp 1
 
Building fast interpreters in Rust
Building fast interpreters in RustBuilding fast interpreters in Rust
Building fast interpreters in Rust
 
An introduction to scala
An introduction to scalaAn introduction to scala
An introduction to scala
 
Jscex: Write Sexy JavaScript
Jscex: Write Sexy JavaScriptJscex: Write Sexy JavaScript
Jscex: Write Sexy JavaScript
 
Jscex: Write Sexy JavaScript (中文)
Jscex: Write Sexy JavaScript (中文)Jscex: Write Sexy JavaScript (中文)
Jscex: Write Sexy JavaScript (中文)
 
Lambda? You Keep Using that Letter
Lambda? You Keep Using that LetterLambda? You Keep Using that Letter
Lambda? You Keep Using that Letter
 
深入浅出Jscex
深入浅出Jscex深入浅出Jscex
深入浅出Jscex
 
High Wizardry in the Land of Scala
High Wizardry in the Land of ScalaHigh Wizardry in the Land of Scala
High Wizardry in the Land of Scala
 
「Frama-Cによるソースコード検証」 (mzp)
「Frama-Cによるソースコード検証」 (mzp)「Frama-Cによるソースコード検証」 (mzp)
「Frama-Cによるソースコード検証」 (mzp)
 
Coffee Scriptでenchant.js
Coffee Scriptでenchant.jsCoffee Scriptでenchant.js
Coffee Scriptでenchant.js
 
Functional programming ii
Functional programming iiFunctional programming ii
Functional programming ii
 
03. haskell refresher quiz
03. haskell refresher quiz03. haskell refresher quiz
03. haskell refresher quiz
 
(How) can we benefit from adopting scala?
(How) can we benefit from adopting scala?(How) can we benefit from adopting scala?
(How) can we benefit from adopting scala?
 
Strinng Classes in c++
Strinng Classes in c++Strinng Classes in c++
Strinng Classes in c++
 
Principles of functional progrmming in scala
Principles of functional progrmming in scalaPrinciples of functional progrmming in scala
Principles of functional progrmming in scala
 
Taylor problem
Taylor problemTaylor problem
Taylor problem
 
TI1220 Lecture 6: First-class Functions
TI1220 Lecture 6: First-class FunctionsTI1220 Lecture 6: First-class Functions
TI1220 Lecture 6: First-class Functions
 
ภาษา C โปรแกรมย่อยและฟังก์ชันมาตรฐาน
ภาษา C โปรแกรมย่อยและฟังก์ชันมาตรฐานภาษา C โปรแกรมย่อยและฟังก์ชันมาตรฐาน
ภาษา C โปรแกรมย่อยและฟังก์ชันมาตรฐาน
 

Recently uploaded

Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdf
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdfRising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdf
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdfOrbitshub
 
Exploring Multimodal Embeddings with Milvus
Exploring Multimodal Embeddings with MilvusExploring Multimodal Embeddings with Milvus
Exploring Multimodal Embeddings with MilvusZilliz
 
Elevate Developer Efficiency & build GenAI Application with Amazon Q​
Elevate Developer Efficiency & build GenAI Application with Amazon Q​Elevate Developer Efficiency & build GenAI Application with Amazon Q​
Elevate Developer Efficiency & build GenAI Application with Amazon Q​Bhuvaneswari Subramani
 
MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024MIND CTI
 
Strategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherStrategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherRemote DBA Services
 
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...Orbitshub
 
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, AdobeApidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobeapidays
 
DEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
DEV meet-up UiPath Document Understanding May 7 2024 AmsterdamDEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
DEV meet-up UiPath Document Understanding May 7 2024 AmsterdamUiPathCommunity
 
Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...
Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...
Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...apidays
 
ICT role in 21st century education and its challenges
ICT role in 21st century education and its challengesICT role in 21st century education and its challenges
ICT role in 21st century education and its challengesrafiqahmad00786416
 
Platformless Horizons for Digital Adaptability
Platformless Horizons for Digital AdaptabilityPlatformless Horizons for Digital Adaptability
Platformless Horizons for Digital AdaptabilityWSO2
 
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin WoodPolkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin WoodJuan lago vázquez
 
Six Myths about Ontologies: The Basics of Formal Ontology
Six Myths about Ontologies: The Basics of Formal OntologySix Myths about Ontologies: The Basics of Formal Ontology
Six Myths about Ontologies: The Basics of Formal Ontologyjohnbeverley2021
 
Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...
Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...
Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...Angeliki Cooney
 
Why Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businessWhy Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businesspanagenda
 
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...apidays
 
Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfsudhanshuwaghmare1
 
[BuildWithAI] Introduction to Gemini.pdf
[BuildWithAI] Introduction to Gemini.pdf[BuildWithAI] Introduction to Gemini.pdf
[BuildWithAI] Introduction to Gemini.pdfSandro Moreira
 
Corporate and higher education May webinar.pptx
Corporate and higher education May webinar.pptxCorporate and higher education May webinar.pptx
Corporate and higher education May webinar.pptxRustici Software
 
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot TakeoffStrategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoffsammart93
 

Recently uploaded (20)

Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdf
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdfRising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdf
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdf
 
Exploring Multimodal Embeddings with Milvus
Exploring Multimodal Embeddings with MilvusExploring Multimodal Embeddings with Milvus
Exploring Multimodal Embeddings with Milvus
 
Elevate Developer Efficiency & build GenAI Application with Amazon Q​
Elevate Developer Efficiency & build GenAI Application with Amazon Q​Elevate Developer Efficiency & build GenAI Application with Amazon Q​
Elevate Developer Efficiency & build GenAI Application with Amazon Q​
 
MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024
 
Strategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherStrategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a Fresher
 
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...
 
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, AdobeApidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
 
DEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
DEV meet-up UiPath Document Understanding May 7 2024 AmsterdamDEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
DEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
 
Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...
Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...
Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...
 
ICT role in 21st century education and its challenges
ICT role in 21st century education and its challengesICT role in 21st century education and its challenges
ICT role in 21st century education and its challenges
 
Platformless Horizons for Digital Adaptability
Platformless Horizons for Digital AdaptabilityPlatformless Horizons for Digital Adaptability
Platformless Horizons for Digital Adaptability
 
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin WoodPolkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
 
Six Myths about Ontologies: The Basics of Formal Ontology
Six Myths about Ontologies: The Basics of Formal OntologySix Myths about Ontologies: The Basics of Formal Ontology
Six Myths about Ontologies: The Basics of Formal Ontology
 
Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...
Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...
Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...
 
Why Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businessWhy Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire business
 
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
 
Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdf
 
[BuildWithAI] Introduction to Gemini.pdf
[BuildWithAI] Introduction to Gemini.pdf[BuildWithAI] Introduction to Gemini.pdf
[BuildWithAI] Introduction to Gemini.pdf
 
Corporate and higher education May webinar.pptx
Corporate and higher education May webinar.pptxCorporate and higher education May webinar.pptx
Corporate and higher education May webinar.pptx
 
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot TakeoffStrategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
 

FunScript 2013 (with speakers notes)

  • 2. Me • Energy trading systems • C#/F#/C++ • Functional zbray.com @zbray * Lots of F# * Calculation Engine * Not a JS expert
  • 3. What is FunScript? // F# Code -> JavaScript Code Compiler.Compile: Expr -> string * F# Code -> JS Code * Quotation Expr -> String * Quotations in F# provide a way of getting the AST from a piece of code.
  • 4. What does it support? • Most F# code • A little mscorlib • 400+ bootstrapped tests * Bootstrapped: FSharp.PowerPack + JInt
  • 5. Primitives • Strings • Numbers (beware!) • Booleans * Ints/Bytes/etc. all converted to number. * Loops that look infinite can turn out to be finite...
  • 6. Flow var _temp1; if (x) let y = { _temp1 = "foo"; if x then "foo" } else else "bar" { _temp1 = "bar"; y }; var y = _temp1; return y; var xs = List_CreateCons(1.000000, List_CreateCons(2.000000, List_CreateCons(3.000000, List_Empty()))); let xs = [1; 2; 3] if ((xs.Tag == "Cons")) { match xs with var _xs = List_Tail(xs); var x = List_Head(xs); | x::xs -> x return x; } | _ -> failwith "never" else { throw ("never"); } * Inline if... then... else... blocks * Pattern matching * While + For loops * Caveat: Quotation Problem: “for x in xs” when xs is an array
  • 7. Functions var isOdd = (function (x) let isOdd x = x % 2 <> 0 { return ((x % 2.000000).CompareTo(0.000000) != 0.000000); isOdd 2 }); return isOdd(2.000000); return (function (x) { (fun x -> x % 2 = 0)(2) return ((x % 2.000000).CompareTo(0.000000) == 0.000000); })(2.000000); * Let bound functions * Anonymous lambda functions * Note/Caveat: CompareTo rather than operators: Allows structural equality. Has negative impact on performance. Cite: Mandelbrot test by Carsten Koenig 100x worse than JS vs. 1000x for Fay.
  • 8. Records type Person = var i_Person__ctor; i_Person__ctor = (function (Name, Age) { Name: string; Age: int } { this.Name = Name; let bob = this.Age = Age; }); { Name = "Bob"; Age = 25 } var bob = (new i_Person__ctor("Bob", 25.000000)); var now = (new i_Person__ctor("Bob", 25.000000)); let now = { Name = "Bob"; Age = 25 } var _temp1; var Age = 26.000000; let soon = { now with Age = 26 } _temp1 = (new i_Person__ctor(now.Name, Age)); var soon = _temp1; ...but also discriminated unions, classes and modules * Most of the types you can define * Records, DUs, Classes, Modules * Records very similar to JSON. * Record expressions are shallow copies with some changes * Records & DUs have structural equality. * Caveat: Class inheritance doesn’t work (yet) * Caveat: DU structural equality is broken on the main branch.
  • 9. Operators let xs = [10 .. 20] var xs = Seq_ToList(Range_oneStep(10.000000, 20.000000)); let xs = [10 .. 2 .. 20] var xs = Seq_ToList(Range_customStep(10.000000, 2.000000, 20.000000)); var incr = (function (x) let incr x = x + 1 { return (x + 1.000000); let x = 10 }); var x = 10.000000; x |> incr return incr(x) var incr = (function (x) { return (x + 1.000000); }); let incr x = x + 1. var divBy2 = (function (x) { let divBy2 x = x / 2. return (x / 2.000000); }); (incr << divBy2) 10. return (function (x) { return incr(divBy2(x)); })(10.000000); * Logic & Arithmetic too (obviously) * But also... identity, ignore, defaultArg, reference assignment etc. * Can also define your own. * See the tests for a complete list.
  • 10. Computation expressions return (function (arg00) { return Async_StartImmediate(arg00, {Tag: "None"}); })((function (builder_) async { return () } { return builder_.Delay((function (unitVar) |> Async.StartImmediate { var _temp3; return builder_.Return(_temp3); })); })(Async_get_async())); * Async workflow built in... * Can define your own too, e.g., the maybe monad if you wanted it * LiveScript has the concept of back calls
  • 11. Data structures • Array • List • Seq • Map • Set • Option
  • 12. Bored yet? Boring bit over (hopefully). We’re half way to the pub.
  • 14. Enormous number of devices. More than .Net or Mono.
  • 15. Not just for the browser. * Desktop Apps. * Tablet/Phone Apps. * Servers.
  • 16. Don’t we have this already? • FSWebTools • WebSharper • Pit • JSIL F# has a long history of compiling to JavaScript Tomas released FSWebTools back in 2006 or 07. CoffeeScript appeared in 2009. But FunScript is focusing on something slightly different...
  • 17. Extensibility We cannot port the whole framework. ... but we can give you the tools to chip off the bits you need.
  • 18. Movie data example Tomas built this web app with FunScript. No .NET the whole thing runs in JS.
  • 19. * Who is familar with type providers? * Like code gen, but without the manual step and can be lazy (which is great for stuff like freebase)...
  • 20. Mapping the Apiary.io type provider • Makes calls to the framework • Not quotation friendly • We replace (or re-route) the calls to quotation friendly methods and types ExpressionReplacer.createUnsafe <@ ApiaryDocument.Create @> <@ JsonProvider.JsRuntime.CreateDocument @> ExpressionReplacer.createUnsafe <@ fun (d:ApiaryDocument) -> d.JsonValue @> <@ JsonProvider.JsRuntime.Identity @> ExpressionReplacer.createUnsafe <@ fun (d:ApiaryDocument) -> d.Context @> <@ getContext @> Compiler.Compile(<@ page() @>, components=FunScript.Data.Components.DataProviders) * We cannot use the provider out of the box... * But because the compiler is EXTENSIBLE we can tell it how to convert those calls. * It [the compiler] will find all call sites and change them. * Then we can use the provider in our JavaScript output * Any questions on that?
  • 21. * OK so... * That’s one feature that existing implementations don’t have. * What else?
  • 22. What about these? Elm See: http://altjs.org/ * Many languages target JavaScript now. * It has become a kind of IL. * Some are quite good. I recommend LiveScript if you don’t mind something dynamic.
  • 23. Dynamically typed • Good at interop • But if its too close to JavaScript... * Can reuse existing libraries * Can consume JS data * But... * Inconsistent operations (annoying on forms) * Dodgy for ... in ... loops, although fixed in most compile to JS languages * Dodgy function scope. Yuck! * Counter-intuitive “Falsey” values * Auto semi-colon insertion
  • 24. Statically typed: FFI sucks * Foreign function interface * Have to map every function you want to use * Tedious and error prone - may as well go dynamic * This is Fay. But same in Roy, js_of_ocaml, etc. * Can do this in FunScript too.
  • 25. The Lonely Island * If you have to use FFI you are a lonely island * Cannot easily access any of the existing JavaScript infrastructure
  • 26. Bypass FFI with type providers * Uses similar techniques to those I described in the Movie example * The TypeScript library creates a bunch of types and tells the compiler how to turn them into JavaScript. * F# is the only language that supports this workflow at the moment!
  • 27. Just the beginning • TypeScript only has mappings for 10s of JavaScript libraries. • Google Closure annotations • JavaScript type inferrer * Google closure might provide many more mappings * JavaScript type inferrer would probably be very hard to build but it would be awesome - EDIT: Colin Bull has already made a little progress towards this: https://github.com/ colinbull/IronJS/commit/612b799351a37d720920d4c68797787d2b72aaca - EDIT: We could even have a type provider to the node package manager (NPM) then we wouldn’t even need to mess around with files. For example: type npmProvider = NodePacakgeManager() let npm = npmProvider.GetContext() let express = npm.express.v3_1_2 let connect = npm.connect.v2_7_2 ...
  • 28. GitHub numbers • JavaScript: #1 • FSharp: #43 Sources: www.github.com/languages/ www.r-chart.com/2010/08/github-stats-on-programming-languages.html So this is the sell... Why should you go out and build me a JavaScript type inferrer... 21% of the projects on GitHub are _labelled_ as JavaScript
  • 29. 2010-2012: http://t.arboreus.com/post/31469214663/visualizing-changes-in-popularity-rankings-of * This is how the popularity of programming languages has changed (according to fairly arbitrary measures) in the last two years. * JavaScript is still on top.
  • 30. LinkedIn numbers JavaScript F# 914,000 people 2,000 people in scale
  • 31. Thanks to the FunScript contributors • Tomas Petricek • Phillip Trelford • James Freiwirth • Robert Pickering • Steffen Forkmann If you’d like to contribute come and talk to me afterwards.
  • 32. Summary • FunScript compiles F# into JavaScript • It is extensible: re-route any method call • F# is the only statically typed language (that capable of taking advantage of I’m aware of) JavaScript libraries without FFI or code-gen