Share
Embed
FullStack 2016 - Elm
Lessons learnt from Functional Programming with Haskell and Elm
Jon Kelly
July 21, 2016
Transcript
51 slides
-
FP lessons from Haskell & Elm Elm app with d3
displays & solves a puzzle How to create a basic elm app, the exact pattern that influenced redux FP building blocks can feel like huge obstacles and how to make use of them IoT gadgets coded with FP Never been easier to build elm app but how easy is that? -
Questions welcome! Time is a bit tight, but it's fine
to ask questions. One to one chats better for the bar later or emails My contact details are at the end, do get in touch Also fine not to understand everything at once, I'm working through a lot of this myself Yesterday's keynote speaker said earlier this year that we are all writing good code now. I completely agree, this talk is to present new ideas, not to downplay anything we're doing now. -
Don't believe everything you hear! I'm not a Haskell programmer,
I just write Haskell programs What follows is how I see/understand things It may or may not exactly match the books, wikis, academic papers, mathematical proofs etc. -
Elm, what's with that, then • Node got me back
doing FP, I've been looking to improve since then • We hear a lot about Elm and it's benefits • However, many people try it and drop it quickly • Why? Is it useful or not? -
FP example code • Wrote Haskell program to solve computer
game puzzle • Converted Haskell to interactive Elm app – It simulates the puzzle and calculates the solution • We'll consider the solution(s) • Can we take lessons from FP back to js ? – We'll see the Elm/Haskell code converted to Angular2,RxJs, Typescript app • Is elm a temporary fad or part of all our futures? -
Time-travel in PuzzleLand • Does someone want to click some
buttons? • How do we get back from here? • Anyone fancy a play with an IoT gadget? -
We are already FP coders! • Lisp (created 1956) is
now on Esp8266 – it's got me thinking! • Map, reduce etc • The blueprint for Js, with some C constructs on top. – No wonder we have such a great time with it! – Private data closure pattern from lisp • Abelson and Sussman’s classic Structure and Interpretation of Computer Programs • ES6 just catching up Lisp 30 years later – backticks, symbols -
How to build a basic Elm app • Model (one
String!) • Update, View • Html is code Pro - great for refactoring Con - rebuild for changes • Fully uni-directional – Just like RxJs, Redux etc -
FP building blocks (or obstacles!) • Unfamiliar data types •
Type signatures • Quick interactive demo of lists • No loops, you're kidding ? – Elm-syntax page, search for loop, there's nothing there! – Map, filter etc -
Haskell type strictness Haskell is relentless in type checking. No
casts or ignore flags … Can decide not to specify type – Haskell complains if this does not hold up It does have the notion of type groups – num, equality … (C# generic constraints) -
Haskell - immutability Nothing changes, we create new things only
Functions have no side effects - Same input - same output, always except for when we have side effects, but let's move on! -
FP types The usual Int, Float, String, Bool suspects Lists
are like arrays Any length – can only hold a single type Tuples are like, er, multiples ? Fixed length – may store multiple types Algebraic create our own from the above (diy) plus a part we specify (e.g. Tree Int) Records object-like syntactic sugar in Elm, a bit duck type-y -
Lists – quick intro Build [1,2,3] like this 1: 2:
3: [] Pass as params like this xs entire list x:xs x is “head”, xs is “tail” (destructuring like es6) FP functions are designed to work with head of list as much as possible -
Recursion, pattern matching Pattern matching – a bit like if
… then … or switch, case factorial 0 = 1 end condition Factorial n = n * factorial (n – 1) recurse step -
Recursion, pattern matching e.g. leng [1, 2, 3] Haskell -
leng [] = 0 end condition leng (x:xs) = 1 + leng xs recurse step Elm - leng xs = Case xs of [] -> 0 end condition x::xs -> 1 + leng xs recurse step -
Map - type signature (a -> b) -> List a
-> List b e.g. List.map (\x -> x + 1) [1, 2, 3] -
Elm state FP langs have different styles of state handling
Haskell – I/O monad (leave for now) Elm state – a bit like juggling, state never touches the ground once started -
Strange stuff on the way This might all seem a
bit weird … Feel free to let it go by ! -
Solution – List operations Wheels represented as lists of Ints
One list is a Wheel Pos TurnWheel int Wheel Pos drop, take are list operations - ideal for small lists, slower for larger lists -
Solution - Recursion List of Wheel Pos Wheel Loop Not
a great name, any suggestions? Created by buildWheelLoop Gives us secLoop, thrLoop and ansLoop As shown in app -
build WheelLoop List WheelPos newP os WheelLoop WheelLoop From StartPos
WheelPos WheelLoop Is called by -
Solution - Map Given first Wheel, and secLoop Use map
to go through secLoop and attach to copy of first item This creates a LoopsPermutation - two loops mixed, perhaps In effect, basis for solution/algorithm – see in app Here, Haskell code is little different from any modern language (that uses an anonymous function) -
TwoWheel Perms WheelPos Wheel Loop List LoopsPermutation ThreeWheel Perms WheelPos
Wheel Loop List LoopsPermutation Wheel Loop -
Solution – sumPlusPerms Go through permutations and add anwers to
each set Add across lists – this is what I wondered about for nought and crosses Here it seems natural enough - for a single column -
Solution – findSpecificAnswer Go through permutations and anwers Trawl through
answers, compare to answers loop Dropwhile is part of a range of elegant functions -
Something better Solution works – not sure it scales well
More on this later Feels big and unwieldy, all those permutations -
Solution – Second version Wanted a way not to build
perms items So keep memory use limited to a small amount Since then, have heard about “constant space” Created a revised version of this, which filters the items before processing -
Solution – Third version Based on early idea More memory
per iteration than second But limited to 2 wheel perms So scales infinitely beyond that -
FP on IoT • All the gadgets are programmed with
FP • FP can be as lightweight as Lua • These programs were written or prototyped in Haskell and Elm, then converted • Bit of a proof of concept, much like micro-python -
Lessons from fp • Write code, optimise later • Write
small code, test it, fit together – pattern from lisp 30 years ago, much like tdd – Do the same with data structures • Types show transformations, search for type pattern, not just code • Tail recursion (waiting on Node for this!) -
Elm/FFI/js/d3 • Works nicely, but raw js can kill off
elm just like anything else • Mechanism for swapping data works fine and it intuitive -
My views • I find that I really trust Elm
• Pros – Solid - failure of Elm app never occurred to me – Type checking saves a lot of work • Cons – Fiddly, breaking changes, wider adoption chances -
Bonus code - RxJs Uni-directional UI RxJs – deals with
infinite streams we can choose to get first item only Typescript – preserves Haskell types They stand out clearly Are they useful? What have we gained or lost by this functional programming style ? -
Bonus code – C# Linq Not so much done here,
but get a flavour Like that the Haskell types transfer well We have lazy eval – we declare operations But nothing happens until x amount of data requested What have we gained or lost by this functional programming style ? -
Thanks for listening Github: https://github.com/jkbits1 Repo: talkUI (nodejs server for
apps) HaskellElmTalk (code only) [email protected] Resources: http://learnyouahaskell.com/ http://guide.elm-lang.org/ https://en.wikibooks.org/wiki/Haskell Lisp original repo: https://github.com/yesco/esp-lisp/wiki