SlideShare una empresa de Scribd logo
1 de 34
Playing functional
Conway’s game of life




       Vagif Abilov
About myself

•   Mail: vagif.abilov@gmail.com
•   Twitter: @ooobject
•   GitHub: object
•   BitBucket: object
•   Blog: http://bloggingabout.net/blogs/vagif/default.aspx
•   Articles: http://www.codeproject.com

The source code for this presentation can be found at
https://github.com/object/ConwayGame
Playing functional
Conway’s game of life




       Vagif Abilov
Conway’s game of life

• Invented in 1970 by the British mathematician John
  Conway
• Zero-player game, its evolution is fully determined by its
  initial state
• The universe of the Game of Life is an infinite two-
  dimensional orthogonal grid of square cells, each of
  which is in one of two possible states, alive or dead

Source: Wikipedia
Rules of Conway’s game of life

1. Any live cell with fewer than two live neighbours dies,
   as if caused by under-population.
2. Any live cell with two or three live neighbours lives on
   to the next generation.
3. Any live cell with more than three live neighbours dies,
   as if by overcrowding.
4. Any dead cell with exactly three live neighbours
   becomes a live cell, as if by reproduction.
Impelemening Conway’s game

How would you approach the implementation?

A small quiz: what names should we introduce?

•   Classes
•   Class properties
•   Class methods
•   Structs
•   Enums
What people say on Twitter



  “How is writing Java like writing classic
 Russian literature? You have to introduce
 100 names before anything can happen.”

                @jamesiry
Speaking about Russian literature

Nightingales, a sigh, a whisper
In a shady nook
And the lullaby in silver
Of a lazy brook.
…

• A short poem by Afanasy Fet (1850)
• 12 lines, not a single verb
Checking other implementations




Source:
http://www.codeproject.com/Articles/185208/Solving-
Conway-s-Game-of-Life-using-State-Pattern
Implementation code metrics

•   5 classes (including 2 subclasses)
•   5 properties
•   5 methods
•   316 lines of code
•   64 effective lines of code (calculated using VS code
    metrics)
Cell state definition

Discussion in comments about cell state definition

• Class (base class with 2 subclasses implementing
  State pattern)
• Enum (Dead, Alive)
• Boolean

What would you choose?
Cell state choice consequence

• No matter what type you choose to represent cell state,
  you will need a cell property to hold it
• Having cells with different property values (Dead and
  Alive) encourages design where both types of cells are
  stored
• Storing cells with different states has negative impact
  on the scalability
• Moreover: it limits the solution to boards of fixed size
• Adding names add constraints!
Imperative languages lessons

• Symbol definition does not necessarily lead to clean
  code
• Names are opinionated, more names – more opinions
• More names – more constraints
• Design patterns are often introduced to patch up
  shortcomings in the language
Entering functional programming



     Conway’s game of life is about
     transforming cell generations

         What if we focus just on
       functional transformations?
Implementation plan

1.   Classical game of life
2.   Multidimensional game of life
3.   Concurrent game of life
4.   Game of life visualization
5.   Surprise, surprise…
Classical game of life
Multidimensional game of life
Asynchronous game of life
Asynchronous burden

• Asynchronous support requires revision of API and its
  implementation
• It is common to offer two (significantly different)
  versions of API: one for synchronous and one for
  asynchronous execution
• Mutable nature of imperative languages require major
  changes if not complete rewrite of components to
  become thread-safe and support asynchronous or
  parallel execution
Asynchronous programming model

• Synchronous:
   – Execute (can be any verb, e.g. Read)


• Asynchronous:
   – BeginExecute (receives AsyncCallback, returns IAsyncResult)
   – EndExecute (receives IAsyncResult object)
   – <Callback> method (receives IAsyncResult)


• File IO example:
   – Read
   – BeginRead, EndRead, <Callback>
Benchmark results


Pattern size*   C# Linq      F#       F# Async    F# PSeq
    10**        0:00.183   0:00.357   0:00.320    0:00.570
     25         0:00.428   0:00.315   0:00.157    0:00.196
     50         0:06.034   0:04.064   0:01.512    0:01.231
    100         1:25.162   1:06.429   0:27.428    0:31.270




* Pattern size N corresponds to a square N * N used to
generate a pattern of N * N / 2 elements

** Pattern size 10 was used to warm up the text fixture
Game of life visualization
Time for surprises




            Life in a tweet

    Living with no sense of monad
Life in a tweet

• A great algorithm should fit in a tweet
• If an algorithm does not fit in a tweet, it’s
  overcomplicated
• But to fit a great algorithm in a tweet you need a great
  programming language
• F# is a great programming language!
Life in a tweet

let f s g = g|>List.mapi(fun i x->match Seq.sumBy(fun o->
g.[abs((i+o)%(s*s))])[-1-s;-s;1-s;-1;1;-1+s;s;1+s]with 3->
1|2->x|_->0)

• Written by Phil Trelfold
  (http://trelford.com/blog/post/140.aspx)
• 127 characters long
Song time!



   Living With No Sense of Monads


        Originally performed by Smokie
          with slightly different words
Living with no sense of monads


I first met Alice in a small bookstore,
"What book, - I asked, - are you looking for?"
And she said: "About monads."

I understood that's a key to her heart,
I had no doubts that I was smart.
It should be easy reading, an easy start...
Living with no sense of monads


But I still don't get this wisdom,
It's really mystic word
I guess it has it's reasons,
Someone gets it, but I don't.
'Cos for twenty-four years
I've been trying to understand the monads.
Living with no sense of monads


Twenty-four years
Just waiting for a chance,
I have to keep on reading,
Maybe get a second glance,
I will never get used to not understanding sense
of monads
Living with no sense of monads


Grew up together,
Went to the same class,
And to be honest:
I was better in math
Than Alice.
Living with no sense of monads


Too old for rock-n-roll - I'm forty four,
Too young for monads - still have a hope.
That the day will come
When I let Alice know...
Living with no sense of monads


But I still don't get this wisdom,
It's really mystic word
I guess it has it's reasons,
Someone gets it, but I don't.
'Cos for twenty-four years
I've been trying to understand the monads.

(all together):
Monads! What the f*ck is monads?!
Living with no sense of monads


Twenty-four years
Just waiting for a chance,
I have to keep on reading,
Maybe get a second glance,
I will never get used to not understanding sense
of monads
Thank you!

•   Mail: vagif.abilov@gmail.com
•   Twitter: @ooobject
•   GitHub: object
•   BitBucket: object
•   Blog: http://bloggingabout.net/blogs/vagif/default.aspx
•   Articles: http://www.codeproject.com

The source code for this presentation can be found at
https://github.com/object/ConwayGame

Más contenido relacionado

Similar a F# in Action: Playing Functional Conway's Game of Life

expect("").length.toBe(1)
expect("").length.toBe(1)expect("").length.toBe(1)
expect("").length.toBe(1)Philip Hofstetter
 
Lesson4.2 u4 l1 binary squences
Lesson4.2 u4 l1 binary squencesLesson4.2 u4 l1 binary squences
Lesson4.2 u4 l1 binary squencesLexume1
 
Pa1 dictionaries subset
Pa1 dictionaries subsetPa1 dictionaries subset
Pa1 dictionaries subsetaiclub_slides
 
Generating Natural-Language Text with Neural Networks
Generating Natural-Language Text with Neural NetworksGenerating Natural-Language Text with Neural Networks
Generating Natural-Language Text with Neural NetworksJonathan Mugan
 
Code retreat @BMW Car IT
Code retreat @BMW Car ITCode retreat @BMW Car IT
Code retreat @BMW Car ITSebastian Benz
 
Hunting for anglerfish in datalakes
Hunting for anglerfish in datalakesHunting for anglerfish in datalakes
Hunting for anglerfish in datalakesDominic Egger
 
[Rakuten TechConf2014] [D-2] The Pattern-Matching-Oriented Programming Langua...
[Rakuten TechConf2014] [D-2] The Pattern-Matching-Oriented Programming Langua...[Rakuten TechConf2014] [D-2] The Pattern-Matching-Oriented Programming Langua...
[Rakuten TechConf2014] [D-2] The Pattern-Matching-Oriented Programming Langua...Rakuten Group, Inc.
 
Sequencing run grief counseling: counting kmers at MG-RAST
Sequencing run grief counseling: counting kmers at MG-RASTSequencing run grief counseling: counting kmers at MG-RAST
Sequencing run grief counseling: counting kmers at MG-RASTwltrimbl
 
Deep Learning with Python (PyData Seattle 2015)
Deep Learning with Python (PyData Seattle 2015)Deep Learning with Python (PyData Seattle 2015)
Deep Learning with Python (PyData Seattle 2015)Alexander Korbonits
 
Meta Programming in Ruby - Code Camp 2010
Meta Programming in Ruby - Code Camp 2010Meta Programming in Ruby - Code Camp 2010
Meta Programming in Ruby - Code Camp 2010ssoroka
 
How To Start An Essay - Makena. Online assignment writing service.
How To Start An Essay - Makena. Online assignment writing service.How To Start An Essay - Makena. Online assignment writing service.
How To Start An Essay - Makena. Online assignment writing service.Luisa Polanco
 
Transition Words Essay Writing - Transition Signals
Transition Words Essay Writing - Transition SignalsTransition Words Essay Writing - Transition Signals
Transition Words Essay Writing - Transition SignalsCynthia Lamarche
 
ECMAScript 2015: my favourite parts
ECMAScript 2015: my favourite partsECMAScript 2015: my favourite parts
ECMAScript 2015: my favourite partsAndré Duarte
 
How To Write A Scientific Abstract - Video Lesson Transcript Study.Com
How To Write A Scientific Abstract - Video Lesson Transcript Study.ComHow To Write A Scientific Abstract - Video Lesson Transcript Study.Com
How To Write A Scientific Abstract - Video Lesson Transcript Study.ComJennifer Nulton
 
IntroPython-Week02-StringsIteration.pptx
IntroPython-Week02-StringsIteration.pptxIntroPython-Week02-StringsIteration.pptx
IntroPython-Week02-StringsIteration.pptxchrisdy932
 
Dark Side of the Net Lecture 2 Cryptography
Dark Side of the Net Lecture 2 CryptographyDark Side of the Net Lecture 2 Cryptography
Dark Side of the Net Lecture 2 CryptographyMarcus Leaning
 
«Applied cryptanalysis stream ciphers» by Vladimir Garbuz
«Applied cryptanalysis stream ciphers» by Vladimir Garbuz «Applied cryptanalysis stream ciphers» by Vladimir Garbuz
«Applied cryptanalysis stream ciphers» by Vladimir Garbuz 0xdec0de
 
Applied cryptanalysis - stream ciphers
Applied cryptanalysis - stream ciphersApplied cryptanalysis - stream ciphers
Applied cryptanalysis - stream ciphersVlad Garbuz
 
Not Everything is an Object - Rocksolid Tour 2013
Not Everything is an Object  - Rocksolid Tour 2013Not Everything is an Object  - Rocksolid Tour 2013
Not Everything is an Object - Rocksolid Tour 2013Gary Short
 

Similar a F# in Action: Playing Functional Conway's Game of Life (20)

expect("").length.toBe(1)
expect("").length.toBe(1)expect("").length.toBe(1)
expect("").length.toBe(1)
 
Lesson4.2 u4 l1 binary squences
Lesson4.2 u4 l1 binary squencesLesson4.2 u4 l1 binary squences
Lesson4.2 u4 l1 binary squences
 
Pa1 dictionaries subset
Pa1 dictionaries subsetPa1 dictionaries subset
Pa1 dictionaries subset
 
Generating Natural-Language Text with Neural Networks
Generating Natural-Language Text with Neural NetworksGenerating Natural-Language Text with Neural Networks
Generating Natural-Language Text with Neural Networks
 
Code retreat @BMW Car IT
Code retreat @BMW Car ITCode retreat @BMW Car IT
Code retreat @BMW Car IT
 
Hunting for anglerfish in datalakes
Hunting for anglerfish in datalakesHunting for anglerfish in datalakes
Hunting for anglerfish in datalakes
 
[Rakuten TechConf2014] [D-2] The Pattern-Matching-Oriented Programming Langua...
[Rakuten TechConf2014] [D-2] The Pattern-Matching-Oriented Programming Langua...[Rakuten TechConf2014] [D-2] The Pattern-Matching-Oriented Programming Langua...
[Rakuten TechConf2014] [D-2] The Pattern-Matching-Oriented Programming Langua...
 
Sequencing run grief counseling: counting kmers at MG-RAST
Sequencing run grief counseling: counting kmers at MG-RASTSequencing run grief counseling: counting kmers at MG-RAST
Sequencing run grief counseling: counting kmers at MG-RAST
 
Deep Learning with Python (PyData Seattle 2015)
Deep Learning with Python (PyData Seattle 2015)Deep Learning with Python (PyData Seattle 2015)
Deep Learning with Python (PyData Seattle 2015)
 
Meta Programming in Ruby - Code Camp 2010
Meta Programming in Ruby - Code Camp 2010Meta Programming in Ruby - Code Camp 2010
Meta Programming in Ruby - Code Camp 2010
 
How To Start An Essay - Makena. Online assignment writing service.
How To Start An Essay - Makena. Online assignment writing service.How To Start An Essay - Makena. Online assignment writing service.
How To Start An Essay - Makena. Online assignment writing service.
 
Transition Words Essay Writing - Transition Signals
Transition Words Essay Writing - Transition SignalsTransition Words Essay Writing - Transition Signals
Transition Words Essay Writing - Transition Signals
 
ECMAScript 2015: my favourite parts
ECMAScript 2015: my favourite partsECMAScript 2015: my favourite parts
ECMAScript 2015: my favourite parts
 
How To Write A Scientific Abstract - Video Lesson Transcript Study.Com
How To Write A Scientific Abstract - Video Lesson Transcript Study.ComHow To Write A Scientific Abstract - Video Lesson Transcript Study.Com
How To Write A Scientific Abstract - Video Lesson Transcript Study.Com
 
IntroPython-Week02-StringsIteration.pptx
IntroPython-Week02-StringsIteration.pptxIntroPython-Week02-StringsIteration.pptx
IntroPython-Week02-StringsIteration.pptx
 
Dark Side of the Net Lecture 2 Cryptography
Dark Side of the Net Lecture 2 CryptographyDark Side of the Net Lecture 2 Cryptography
Dark Side of the Net Lecture 2 Cryptography
 
«Applied cryptanalysis stream ciphers» by Vladimir Garbuz
«Applied cryptanalysis stream ciphers» by Vladimir Garbuz «Applied cryptanalysis stream ciphers» by Vladimir Garbuz
«Applied cryptanalysis stream ciphers» by Vladimir Garbuz
 
Applied cryptanalysis - stream ciphers
Applied cryptanalysis - stream ciphersApplied cryptanalysis - stream ciphers
Applied cryptanalysis - stream ciphers
 
Not Everything is an Object - Rocksolid Tour 2013
Not Everything is an Object  - Rocksolid Tour 2013Not Everything is an Object  - Rocksolid Tour 2013
Not Everything is an Object - Rocksolid Tour 2013
 
frames.pptx
frames.pptxframes.pptx
frames.pptx
 

Más de Vagif Abilov

А нам-то зачем функциональное программирование?
А нам-то зачем функциональное программирование?А нам-то зачем функциональное программирование?
А нам-то зачем функциональное программирование?Vagif Abilov
 
Cross-platform Mobile Development using Portable Class Libraries
Cross-platform Mobile Development using Portable Class LibrariesCross-platform Mobile Development using Portable Class Libraries
Cross-platform Mobile Development using Portable Class LibrariesVagif Abilov
 
Staying Close to Experts with Executable Specifications
Staying Close to Experts with Executable SpecificationsStaying Close to Experts with Executable Specifications
Staying Close to Experts with Executable SpecificationsVagif Abilov
 
SOLID Programming with Portable Class Libraries
SOLID Programming with Portable Class LibrariesSOLID Programming with Portable Class Libraries
SOLID Programming with Portable Class LibrariesVagif Abilov
 
Typed? Dynamic? Both! Cross-platform DSLs in C#
Typed? Dynamic? Both! Cross-platform DSLs in C#Typed? Dynamic? Both! Cross-platform DSLs in C#
Typed? Dynamic? Both! Cross-platform DSLs in C#Vagif Abilov
 
Путь к чистому и компактному коду исполняемых спецификаций
Путь к чистому и компактному коду исполняемых спецификацийПуть к чистому и компактному коду исполняемых спецификаций
Путь к чистому и компактному коду исполняемых спецификацийVagif Abilov
 
Executable Specifications in Action
Executable Specifications in ActionExecutable Specifications in Action
Executable Specifications in ActionVagif Abilov
 

Más de Vagif Abilov (8)

А нам-то зачем функциональное программирование?
А нам-то зачем функциональное программирование?А нам-то зачем функциональное программирование?
А нам-то зачем функциональное программирование?
 
Cross-platform Mobile Development using Portable Class Libraries
Cross-platform Mobile Development using Portable Class LibrariesCross-platform Mobile Development using Portable Class Libraries
Cross-platform Mobile Development using Portable Class Libraries
 
Staying Close to Experts with Executable Specifications
Staying Close to Experts with Executable SpecificationsStaying Close to Experts with Executable Specifications
Staying Close to Experts with Executable Specifications
 
SOLID Programming with Portable Class Libraries
SOLID Programming with Portable Class LibrariesSOLID Programming with Portable Class Libraries
SOLID Programming with Portable Class Libraries
 
Typed? Dynamic? Both! Cross-platform DSLs in C#
Typed? Dynamic? Both! Cross-platform DSLs in C#Typed? Dynamic? Both! Cross-platform DSLs in C#
Typed? Dynamic? Both! Cross-platform DSLs in C#
 
Путь к чистому и компактному коду исполняемых спецификаций
Путь к чистому и компактному коду исполняемых спецификацийПуть к чистому и компактному коду исполняемых спецификаций
Путь к чистому и компактному коду исполняемых спецификаций
 
Practical OData
Practical ODataPractical OData
Practical OData
 
Executable Specifications in Action
Executable Specifications in ActionExecutable Specifications in Action
Executable Specifications in Action
 

Último

Scanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL CertsScanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL CertsRizwan Syed
 
The Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptx
The Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptxThe Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptx
The Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptxLoriGlavin3
 
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek SchlawackFwdays
 
Use of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptx
Use of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptxUse of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptx
Use of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptxLoriGlavin3
 
SAP Build Work Zone - Overview L2-L3.pptx
SAP Build Work Zone - Overview L2-L3.pptxSAP Build Work Zone - Overview L2-L3.pptx
SAP Build Work Zone - Overview L2-L3.pptxNavinnSomaal
 
The State of Passkeys with FIDO Alliance.pptx
The State of Passkeys with FIDO Alliance.pptxThe State of Passkeys with FIDO Alliance.pptx
The State of Passkeys with FIDO Alliance.pptxLoriGlavin3
 
What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024Stephanie Beckett
 
TrustArc Webinar - How to Build Consumer Trust Through Data Privacy
TrustArc Webinar - How to Build Consumer Trust Through Data PrivacyTrustArc Webinar - How to Build Consumer Trust Through Data Privacy
TrustArc Webinar - How to Build Consumer Trust Through Data PrivacyTrustArc
 
Passkey Providers and Enabling Portability: FIDO Paris Seminar.pptx
Passkey Providers and Enabling Portability: FIDO Paris Seminar.pptxPasskey Providers and Enabling Portability: FIDO Paris Seminar.pptx
Passkey Providers and Enabling Portability: FIDO Paris Seminar.pptxLoriGlavin3
 
Dev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio WebDev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio WebUiPathCommunity
 
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)Mark Simos
 
How to write a Business Continuity Plan
How to write a Business Continuity PlanHow to write a Business Continuity Plan
How to write a Business Continuity PlanDatabarracks
 
Commit 2024 - Secret Management made easy
Commit 2024 - Secret Management made easyCommit 2024 - Secret Management made easy
Commit 2024 - Secret Management made easyAlfredo García Lavilla
 
Gen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdfGen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdfAddepto
 
Moving Beyond Passwords: FIDO Paris Seminar.pdf
Moving Beyond Passwords: FIDO Paris Seminar.pdfMoving Beyond Passwords: FIDO Paris Seminar.pdf
Moving Beyond Passwords: FIDO Paris Seminar.pdfLoriGlavin3
 
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptx
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptxMerck Moving Beyond Passwords: FIDO Paris Seminar.pptx
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptxLoriGlavin3
 
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024BookNet Canada
 
unit 4 immunoblotting technique complete.pptx
unit 4 immunoblotting technique complete.pptxunit 4 immunoblotting technique complete.pptx
unit 4 immunoblotting technique complete.pptxBkGupta21
 
Digital Identity is Under Attack: FIDO Paris Seminar.pptx
Digital Identity is Under Attack: FIDO Paris Seminar.pptxDigital Identity is Under Attack: FIDO Paris Seminar.pptx
Digital Identity is Under Attack: FIDO Paris Seminar.pptxLoriGlavin3
 
SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024Lorenzo Miniero
 

Último (20)

Scanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL CertsScanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL Certs
 
The Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptx
The Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptxThe Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptx
The Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptx
 
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
 
Use of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptx
Use of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptxUse of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptx
Use of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptx
 
SAP Build Work Zone - Overview L2-L3.pptx
SAP Build Work Zone - Overview L2-L3.pptxSAP Build Work Zone - Overview L2-L3.pptx
SAP Build Work Zone - Overview L2-L3.pptx
 
The State of Passkeys with FIDO Alliance.pptx
The State of Passkeys with FIDO Alliance.pptxThe State of Passkeys with FIDO Alliance.pptx
The State of Passkeys with FIDO Alliance.pptx
 
What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024
 
TrustArc Webinar - How to Build Consumer Trust Through Data Privacy
TrustArc Webinar - How to Build Consumer Trust Through Data PrivacyTrustArc Webinar - How to Build Consumer Trust Through Data Privacy
TrustArc Webinar - How to Build Consumer Trust Through Data Privacy
 
Passkey Providers and Enabling Portability: FIDO Paris Seminar.pptx
Passkey Providers and Enabling Portability: FIDO Paris Seminar.pptxPasskey Providers and Enabling Portability: FIDO Paris Seminar.pptx
Passkey Providers and Enabling Portability: FIDO Paris Seminar.pptx
 
Dev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio WebDev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio Web
 
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
 
How to write a Business Continuity Plan
How to write a Business Continuity PlanHow to write a Business Continuity Plan
How to write a Business Continuity Plan
 
Commit 2024 - Secret Management made easy
Commit 2024 - Secret Management made easyCommit 2024 - Secret Management made easy
Commit 2024 - Secret Management made easy
 
Gen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdfGen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdf
 
Moving Beyond Passwords: FIDO Paris Seminar.pdf
Moving Beyond Passwords: FIDO Paris Seminar.pdfMoving Beyond Passwords: FIDO Paris Seminar.pdf
Moving Beyond Passwords: FIDO Paris Seminar.pdf
 
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptx
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptxMerck Moving Beyond Passwords: FIDO Paris Seminar.pptx
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptx
 
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
 
unit 4 immunoblotting technique complete.pptx
unit 4 immunoblotting technique complete.pptxunit 4 immunoblotting technique complete.pptx
unit 4 immunoblotting technique complete.pptx
 
Digital Identity is Under Attack: FIDO Paris Seminar.pptx
Digital Identity is Under Attack: FIDO Paris Seminar.pptxDigital Identity is Under Attack: FIDO Paris Seminar.pptx
Digital Identity is Under Attack: FIDO Paris Seminar.pptx
 
SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024
 

F# in Action: Playing Functional Conway's Game of Life

  • 1. Playing functional Conway’s game of life Vagif Abilov
  • 2. About myself • Mail: vagif.abilov@gmail.com • Twitter: @ooobject • GitHub: object • BitBucket: object • Blog: http://bloggingabout.net/blogs/vagif/default.aspx • Articles: http://www.codeproject.com The source code for this presentation can be found at https://github.com/object/ConwayGame
  • 3. Playing functional Conway’s game of life Vagif Abilov
  • 4. Conway’s game of life • Invented in 1970 by the British mathematician John Conway • Zero-player game, its evolution is fully determined by its initial state • The universe of the Game of Life is an infinite two- dimensional orthogonal grid of square cells, each of which is in one of two possible states, alive or dead Source: Wikipedia
  • 5. Rules of Conway’s game of life 1. Any live cell with fewer than two live neighbours dies, as if caused by under-population. 2. Any live cell with two or three live neighbours lives on to the next generation. 3. Any live cell with more than three live neighbours dies, as if by overcrowding. 4. Any dead cell with exactly three live neighbours becomes a live cell, as if by reproduction.
  • 6. Impelemening Conway’s game How would you approach the implementation? A small quiz: what names should we introduce? • Classes • Class properties • Class methods • Structs • Enums
  • 7. What people say on Twitter “How is writing Java like writing classic Russian literature? You have to introduce 100 names before anything can happen.” @jamesiry
  • 8. Speaking about Russian literature Nightingales, a sigh, a whisper In a shady nook And the lullaby in silver Of a lazy brook. … • A short poem by Afanasy Fet (1850) • 12 lines, not a single verb
  • 10. Implementation code metrics • 5 classes (including 2 subclasses) • 5 properties • 5 methods • 316 lines of code • 64 effective lines of code (calculated using VS code metrics)
  • 11. Cell state definition Discussion in comments about cell state definition • Class (base class with 2 subclasses implementing State pattern) • Enum (Dead, Alive) • Boolean What would you choose?
  • 12. Cell state choice consequence • No matter what type you choose to represent cell state, you will need a cell property to hold it • Having cells with different property values (Dead and Alive) encourages design where both types of cells are stored • Storing cells with different states has negative impact on the scalability • Moreover: it limits the solution to boards of fixed size • Adding names add constraints!
  • 13. Imperative languages lessons • Symbol definition does not necessarily lead to clean code • Names are opinionated, more names – more opinions • More names – more constraints • Design patterns are often introduced to patch up shortcomings in the language
  • 14. Entering functional programming Conway’s game of life is about transforming cell generations What if we focus just on functional transformations?
  • 15. Implementation plan 1. Classical game of life 2. Multidimensional game of life 3. Concurrent game of life 4. Game of life visualization 5. Surprise, surprise…
  • 19. Asynchronous burden • Asynchronous support requires revision of API and its implementation • It is common to offer two (significantly different) versions of API: one for synchronous and one for asynchronous execution • Mutable nature of imperative languages require major changes if not complete rewrite of components to become thread-safe and support asynchronous or parallel execution
  • 20. Asynchronous programming model • Synchronous: – Execute (can be any verb, e.g. Read) • Asynchronous: – BeginExecute (receives AsyncCallback, returns IAsyncResult) – EndExecute (receives IAsyncResult object) – <Callback> method (receives IAsyncResult) • File IO example: – Read – BeginRead, EndRead, <Callback>
  • 21. Benchmark results Pattern size* C# Linq F# F# Async F# PSeq 10** 0:00.183 0:00.357 0:00.320 0:00.570 25 0:00.428 0:00.315 0:00.157 0:00.196 50 0:06.034 0:04.064 0:01.512 0:01.231 100 1:25.162 1:06.429 0:27.428 0:31.270 * Pattern size N corresponds to a square N * N used to generate a pattern of N * N / 2 elements ** Pattern size 10 was used to warm up the text fixture
  • 22. Game of life visualization
  • 23. Time for surprises Life in a tweet Living with no sense of monad
  • 24. Life in a tweet • A great algorithm should fit in a tweet • If an algorithm does not fit in a tweet, it’s overcomplicated • But to fit a great algorithm in a tweet you need a great programming language • F# is a great programming language!
  • 25. Life in a tweet let f s g = g|>List.mapi(fun i x->match Seq.sumBy(fun o-> g.[abs((i+o)%(s*s))])[-1-s;-s;1-s;-1;1;-1+s;s;1+s]with 3-> 1|2->x|_->0) • Written by Phil Trelfold (http://trelford.com/blog/post/140.aspx) • 127 characters long
  • 26. Song time! Living With No Sense of Monads Originally performed by Smokie with slightly different words
  • 27. Living with no sense of monads I first met Alice in a small bookstore, "What book, - I asked, - are you looking for?" And she said: "About monads." I understood that's a key to her heart, I had no doubts that I was smart. It should be easy reading, an easy start...
  • 28. Living with no sense of monads But I still don't get this wisdom, It's really mystic word I guess it has it's reasons, Someone gets it, but I don't. 'Cos for twenty-four years I've been trying to understand the monads.
  • 29. Living with no sense of monads Twenty-four years Just waiting for a chance, I have to keep on reading, Maybe get a second glance, I will never get used to not understanding sense of monads
  • 30. Living with no sense of monads Grew up together, Went to the same class, And to be honest: I was better in math Than Alice.
  • 31. Living with no sense of monads Too old for rock-n-roll - I'm forty four, Too young for monads - still have a hope. That the day will come When I let Alice know...
  • 32. Living with no sense of monads But I still don't get this wisdom, It's really mystic word I guess it has it's reasons, Someone gets it, but I don't. 'Cos for twenty-four years I've been trying to understand the monads. (all together): Monads! What the f*ck is monads?!
  • 33. Living with no sense of monads Twenty-four years Just waiting for a chance, I have to keep on reading, Maybe get a second glance, I will never get used to not understanding sense of monads
  • 34. Thank you! • Mail: vagif.abilov@gmail.com • Twitter: @ooobject • GitHub: object • BitBucket: object • Blog: http://bloggingabout.net/blogs/vagif/default.aspx • Articles: http://www.codeproject.com The source code for this presentation can be found at https://github.com/object/ConwayGame

Notas del editor

  1. Popular choice: code retreats, coding dojos, pair programmingNext: job interview, define some names
  2. Next: Russian literature
  3. Next: implementation from CodeProject
  4. Next: how would you define State property?
  5. Why state pattern and not enumerators?“Enumerators are amateurish”Next: consequences and constraints
  6. Next:imperative language sessions
  7. Next : getting functional
  8. Next: implementation plan