SlideShare uma empresa Scribd logo
1 de 42
Baixar para ler offline
Learning FP
   Lev Walkin
   @levwalkin
Myself

Founder, Chief Editor of a peer-reviewed
«Practice of Functional Programming»
journal http://fprog.ru/

CTO Echo, a venture backed company
http://aboutecho.com/

Proficient in N languages, M of them FP
Echo

50,000+ HTTP requests per second

500,000+ simultaneous users on site

1,527,721,774 search queries last month

JavaScript, Clojure, Haskell, C, LAMP, RoR,
OCaml, Python, Perl, Visual Basic, C++
What’s your reason
   to learn FP?

1. You already suspect that FP approach
   works best for your domain

2. You want to learn FP to expand your tool
   set
Mature options

Haskell (OCaml, F#)

Scala

Clojure (CL, Scheme)

Erlang
Statically typed

Haskell, OCaml, F# — part of ML family

Utilize Hindley—Milner type inference

You might not even SEE any types

Types provide useful documentation
Statically typed
Scala

Very sophisticated type system

Type inference fails often (you have to
annotate with types)

Lots of syntax sugar, lots of ways to do
things
Type inference

-- Haskell program

main = print “Hello, world!”

(* OCaml program *)

let main = print_string “Hello, world!”
Explicit types

-- Haskell program
main :: IO ()
main = print “Hello, world!”

(* OCaml program *)
val main : unit
let main = print_string “Hello, world!”
Dynamically typed


LISP (type annotations are NOT static
types)

Erlang (Dialyzer helps a bit)
Pure FP training


...requires pure language.

Haskell is the only viable option.
Purity in Haskell

Function have no side effects

All state changes are only through
specially constructed monads (IO, ST)

Static types force isolation

Lazyness thrown in for a deeper fun
Haskell
Medium-size syntax, relatively easy to
learn, but...
Simple & interesting things are EASY
Yet, there are LOTS of abstractions and
approaches to learn: Type classes,
Monads, Arrows, parsing, pretty-printing.
This is why we chose Haskell, right?
“One”




        “silly”   “example.”
Haskell, OCaml, F#
data Tree a =
!    Leaf a
! | Node (Tree a) (Tree a)

type ‘a tree =
! | Leaf of ‘a
! | Node of ‘a tree * ‘a tree

type Tree<'a> =
  | Leaf of ‘a
  | Branch of ‘a Tree * ‘a Tree

               http://fprog.ru/2009/issue2/roman-dushkin-algebraic-data-types/
“One”
   3



        “silly”   “example.”
            5           8
Haskell
data Tree String =
!    Leaf String
! | Node (Tree String) (Tree String)

strToLenTree :: Tree String ! Tree Int

strToLenTree   (Leaf s) = Leaf (length s)
strToLenTree   (Node left right) =
! ! ! Node     (strToLenTree left)
! ! ! ! !      (strToLenTree right)
Haskell
data Tree a =
!    Leaf a
! | Node (Tree a) (Tree a)

mapTree :: (a ! b) ! Tree a ! Tree b

mapTree   f   (Leaf   x) = Leaf (f x)
mapTree   f   (Node   left right) =
! ! !     !    Node   (mapTree f left)
! ! !     !    ! !    (mapTree f right)

strToLenTree :: Tree String ! Tree Int
strToLenTree = mapTree length
Prototyping
[~]> ghci tree.hs
GHCi, version 7.0.4 :? for help
[1 of 1] Compiling Main   ( tree.hs, interpreted )
Ok, modules loaded: Main.
*Main> let tree = Node (Leaf "An") (Leaf "example")
*Main> mapTree (s -> length s) tree
Node (Leaf 2) (Leaf 7)
*Main> mapTree (s -> filter Data.Char.isUpper s) tree
Node (Leaf "A") (Leaf "")
*Main> mapTree (filter Data.Char.isLower) tree
Node (Leaf "n") (Leaf "example")

*Main> :t mapTree
mapTree :: (a -> b) -> Tree a -> Tree b
*Main> :t mapTree length
mapTree length :: Tree [a] -> Tree Int
LISP
Clojure: immutability, persistent data
structures, JVM

Scheme: very small language, suitable for
teaching/learning

Common Lisp: it is a fat multiparadigm
language and has everything (though
parts may be rotten a bit)
Erlang

Simple language

Telecom systems, 24/7, системы
массового обслуживания (web?)

Hot code reload, deep introspection,
embedded facilities for easier clustering
Erlang

% Reverse a string
reverse(String) -> reverse2(String, []).

% Reverse with an accumulator
reverse2([           ], Acc) -> Acc;
reverse2([Head | Tail], Acc) ->
! reverse2(Tail, [Head | Acc]).
Erlang

% Sends request to the [remote] system
% and waits for the response back
send_and_wait(Pid, Message, Timeout) ->
! Pid ! Message,
! receive
! ! Response -> {ok, Response}
! after
! ! Timeout -> {error, timeout}
! end.
Clojure vs LISP*
NEW language, with sound idioms

Immutable data structures are idiomatic

Fast pace of development

JVM may be a big bon for some

Learn it if you want sound, practical
language
                 http://tonsky.livejournal.com/tag/clojure
Scheme vs LISP*

Small, simple language (R5RS)

A basis for SICP — Structure and
Interpretation of Computer Programs

Learn SICP if you want to study
Programming
CL vs LISP*

Many complex ideas mixed in

No enforcement of a good style — you
have to do it on your own

Learn it if you want unrestricted power
Haskell vs ML*

More sound type system

LOTS of language research happen on
Haskell

Learn it if you want to learn FP

Learn it if it fits your domain well

            http://www.ozon.ru/context/detail/id/8696277/
OCaml

Several mostly compatible syntaxes
You can always create a mutable variable
or class field, though not idiomatic
Clearer semantics and computation
model (straightforward translation to
assembly)

 http://mirror.ocamlcore.org/ocaml-tutorial.org/the_basics.html
OCaml vs ML*

OCaml is to Haskell as C is to C++

Poor library support

FAST (on 1-core systems)

Learn it if you want a practical tool and
not satisfied with Haskell or F#
 http://www.slideshare.net/michielovereem/beyond-functional-
            programming-in-haskell-an-introduction-to-ocaml
F# vs ML*

Works under Microsoft .Net

F# on Mono is somewhat usable
Learn it if you want to tinker with FP on
MS platform


           http://www.ozon.ru/context/detail/id/6151130/
Erlang vs *
SMALL language, somewhat bigger OTP

Great support for concurrency (Actors),
and parallelism

Hot code reload & run time introspection

OOP on the outside; FP on the inside

Learn it if you build 24/7 production
system
Scala vs *

Big language, a functional C++ of sorts

JVM

Learn it if you want a great tool, not
satisfied with Java, yet have no
appreciation for true elegance (Clojure)
Learning FP

Haskell provides models and abstractions
(read papers) — pure FP

Scheme teaches you Programming (read
SICP)

Everything else is too practical
Practicing FP
.Net → F#

JVM → Clojure (elegance and simplicity),
Scala (less restrictions)

!{.Net|JVM} → OCaml (if you do not need
libraries), Clojure, Haskell (if you have
balls)

24/7 → Erlang
For individuals

You want flexible system which allows
you to cut corners

Common Lisp

Scala

F#
For teams
You want to think about lifecycle,
support, maintenance, group dynamics

OCaml (static typing provides some
guarantees)

Erlang (simple and straightforward,
designed to withstand errors, good for
novices)
For teams

Scala gets increasingly popular because
people do not appreciate elegance and
sound restrictions

People will throw up in a few years
working with accumulated Scala code

...like C++

                 http://ru.xored.com/2012/12/02/scala/
Haskell resources


Мягкое введение в Haskell

Изучай Haskell во имя добра!




       http://www.rsdn.ru/article/haskell/haskell_part1.xml
Clojure resources


1. Learn spoken English

2. Журнал Никиты Прокопова (tonsky@LJ)
   содержит ссылки и рекомендации



                  http://tonsky.livejournal.com/tag/clojure
Erlang resources


1. Programming Erlang: Software for a
   Concurrent World

2. http://learnyousomeerlang.com



             http://www.ozon.ru/context/detail/id/3645143/
Shameless plug

Журнал «Практика
функционального
программирования»

fprog.ru

@fprogru
Thank you!
Questions?
  @levwalkin

Mais conteúdo relacionado

Destaque

Алексей Ситников. Итоговая презентация группы « Социальная политика». 19 апреля
Алексей Ситников. Итоговая презентация группы « Социальная политика». 19 апреляАлексей Ситников. Итоговая презентация группы « Социальная политика». 19 апреля
Алексей Ситников. Итоговая презентация группы « Социальная политика». 19 апреляDaria Oreshkina
 
Дмитрий Еманов — Под капотом серверного ПО
Дмитрий Еманов — Под капотом серверного ПОДмитрий Еманов — Под капотом серверного ПО
Дмитрий Еманов — Под капотом серверного ПОDaria Oreshkina
 
Антон Веретенников и Илья Семаков. Презентация
Антон Веретенников и Илья Семаков. ПрезентацияАнтон Веретенников и Илья Семаков. Презентация
Антон Веретенников и Илья Семаков. ПрезентацияDaria Oreshkina
 
Сергей Парамонов — Что наша жизнь — игра!
Сергей Парамонов — Что наша жизнь — игра!Сергей Парамонов — Что наша жизнь — игра!
Сергей Парамонов — Что наша жизнь — игра!Daria Oreshkina
 
Максим Семенкин — Открытие
Максим Семенкин — ОткрытиеМаксим Семенкин — Открытие
Максим Семенкин — ОткрытиеDaria Oreshkina
 
Алексей Шалдышев — Проектное управление
Алексей Шалдышев — Проектное управлениеАлексей Шалдышев — Проектное управление
Алексей Шалдышев — Проектное управлениеDaria Oreshkina
 
Наталья Желнова — Как обзавестись аналитиками и получить от них пользу в проекте
Наталья Желнова — Как обзавестись аналитиками и получить от них пользу в проектеНаталья Желнова — Как обзавестись аналитиками и получить от них пользу в проекте
Наталья Желнова — Как обзавестись аналитиками и получить от них пользу в проектеDaria Oreshkina
 
Антон Каляев — Быстрое развертывание среды с Vagrant
Антон Каляев — Быстрое развертывание среды с VagrantАнтон Каляев — Быстрое развертывание среды с Vagrant
Антон Каляев — Быстрое развертывание среды с VagrantDaria Oreshkina
 
Артём Рудаковский — Как мы электронное правительство делали
Артём Рудаковский — Как мы электронное правительство делалиАртём Рудаковский — Как мы электронное правительство делали
Артём Рудаковский — Как мы электронное правительство делалиDaria Oreshkina
 
Асхат Уразбаев — Value Stream Mapping
Асхат Уразбаев — Value Stream MappingАсхат Уразбаев — Value Stream Mapping
Асхат Уразбаев — Value Stream MappingDaria Oreshkina
 
Александр Жарков — Эволюция команды разработки: взгляд изнутри
Александр Жарков — Эволюция команды разработки: взгляд изнутриАлександр Жарков — Эволюция команды разработки: взгляд изнутри
Александр Жарков — Эволюция команды разработки: взгляд изнутриDaria Oreshkina
 
Иван Евтухович — Как перестать релизиться и начать жить
Иван Евтухович — Как перестать релизиться и начать житьИван Евтухович — Как перестать релизиться и начать жить
Иван Евтухович — Как перестать релизиться и начать житьDaria Oreshkina
 
Валкин, Мокевнин — Развитие IT-среды в Ульяновске
Валкин, Мокевнин — Развитие IT-среды в УльяновскеВалкин, Мокевнин — Развитие IT-среды в Ульяновске
Валкин, Мокевнин — Развитие IT-среды в УльяновскеDaria Oreshkina
 
Кирилл Мокевнин — Ментальное программирование
Кирилл Мокевнин — Ментальное программированиеКирилл Мокевнин — Ментальное программирование
Кирилл Мокевнин — Ментальное программированиеDaria Oreshkina
 

Destaque (14)

Алексей Ситников. Итоговая презентация группы « Социальная политика». 19 апреля
Алексей Ситников. Итоговая презентация группы « Социальная политика». 19 апреляАлексей Ситников. Итоговая презентация группы « Социальная политика». 19 апреля
Алексей Ситников. Итоговая презентация группы « Социальная политика». 19 апреля
 
Дмитрий Еманов — Под капотом серверного ПО
Дмитрий Еманов — Под капотом серверного ПОДмитрий Еманов — Под капотом серверного ПО
Дмитрий Еманов — Под капотом серверного ПО
 
Антон Веретенников и Илья Семаков. Презентация
Антон Веретенников и Илья Семаков. ПрезентацияАнтон Веретенников и Илья Семаков. Презентация
Антон Веретенников и Илья Семаков. Презентация
 
Сергей Парамонов — Что наша жизнь — игра!
Сергей Парамонов — Что наша жизнь — игра!Сергей Парамонов — Что наша жизнь — игра!
Сергей Парамонов — Что наша жизнь — игра!
 
Максим Семенкин — Открытие
Максим Семенкин — ОткрытиеМаксим Семенкин — Открытие
Максим Семенкин — Открытие
 
Алексей Шалдышев — Проектное управление
Алексей Шалдышев — Проектное управлениеАлексей Шалдышев — Проектное управление
Алексей Шалдышев — Проектное управление
 
Наталья Желнова — Как обзавестись аналитиками и получить от них пользу в проекте
Наталья Желнова — Как обзавестись аналитиками и получить от них пользу в проектеНаталья Желнова — Как обзавестись аналитиками и получить от них пользу в проекте
Наталья Желнова — Как обзавестись аналитиками и получить от них пользу в проекте
 
Антон Каляев — Быстрое развертывание среды с Vagrant
Антон Каляев — Быстрое развертывание среды с VagrantАнтон Каляев — Быстрое развертывание среды с Vagrant
Антон Каляев — Быстрое развертывание среды с Vagrant
 
Артём Рудаковский — Как мы электронное правительство делали
Артём Рудаковский — Как мы электронное правительство делалиАртём Рудаковский — Как мы электронное правительство делали
Артём Рудаковский — Как мы электронное правительство делали
 
Асхат Уразбаев — Value Stream Mapping
Асхат Уразбаев — Value Stream MappingАсхат Уразбаев — Value Stream Mapping
Асхат Уразбаев — Value Stream Mapping
 
Александр Жарков — Эволюция команды разработки: взгляд изнутри
Александр Жарков — Эволюция команды разработки: взгляд изнутриАлександр Жарков — Эволюция команды разработки: взгляд изнутри
Александр Жарков — Эволюция команды разработки: взгляд изнутри
 
Иван Евтухович — Как перестать релизиться и начать жить
Иван Евтухович — Как перестать релизиться и начать житьИван Евтухович — Как перестать релизиться и начать жить
Иван Евтухович — Как перестать релизиться и начать жить
 
Валкин, Мокевнин — Развитие IT-среды в Ульяновске
Валкин, Мокевнин — Развитие IT-среды в УльяновскеВалкин, Мокевнин — Развитие IT-среды в Ульяновске
Валкин, Мокевнин — Развитие IT-среды в Ульяновске
 
Кирилл Мокевнин — Ментальное программирование
Кирилл Мокевнин — Ментальное программированиеКирилл Мокевнин — Ментальное программирование
Кирилл Мокевнин — Ментальное программирование
 

Semelhante a Лев Валкин — Программируем функционально

Erlang Message Passing Concurrency, For The Win
Erlang  Message  Passing  Concurrency,  For  The  WinErlang  Message  Passing  Concurrency,  For  The  Win
Erlang Message Passing Concurrency, For The Winl xf
 
code4lib 2011 preconference: What's New in Solr (since 1.4.1)
code4lib 2011 preconference: What's New in Solr (since 1.4.1)code4lib 2011 preconference: What's New in Solr (since 1.4.1)
code4lib 2011 preconference: What's New in Solr (since 1.4.1)Erik Hatcher
 
Programming in Computational Biology
Programming in Computational BiologyProgramming in Computational Biology
Programming in Computational BiologyAtreyiB
 
Ruby on Rails (RoR) as a back-end processor for Apex
Ruby on Rails (RoR) as a back-end processor for Apex Ruby on Rails (RoR) as a back-end processor for Apex
Ruby on Rails (RoR) as a back-end processor for Apex Espen Brækken
 
Introduction to Haskell: 2011-04-13
Introduction to Haskell: 2011-04-13Introduction to Haskell: 2011-04-13
Introduction to Haskell: 2011-04-13Jay Coskey
 
Scala - The Simple Parts, SFScala presentation
Scala - The Simple Parts, SFScala presentationScala - The Simple Parts, SFScala presentation
Scala - The Simple Parts, SFScala presentationMartin Odersky
 
ABRIDGED VERSION - Joys & frustrations of putting 34,000 lines of Haskell in...
 ABRIDGED VERSION - Joys & frustrations of putting 34,000 lines of Haskell in... ABRIDGED VERSION - Joys & frustrations of putting 34,000 lines of Haskell in...
ABRIDGED VERSION - Joys & frustrations of putting 34,000 lines of Haskell in...Saurabh Nanda
 
Erlang kickstart
Erlang kickstartErlang kickstart
Erlang kickstartRyan Brown
 
BayFP: Concurrent and Multicore Haskell
BayFP: Concurrent and Multicore HaskellBayFP: Concurrent and Multicore Haskell
BayFP: Concurrent and Multicore HaskellBryan O'Sullivan
 
Managing large datasets in R – ff examples and concepts
Managing large datasets in R – ff examples and conceptsManaging large datasets in R – ff examples and concepts
Managing large datasets in R – ff examples and conceptsAjay Ohri
 
Scala Talk at FOSDEM 2009
Scala Talk at FOSDEM 2009Scala Talk at FOSDEM 2009
Scala Talk at FOSDEM 2009Martin Odersky
 
What we can learn from Rebol?
What we can learn from Rebol?What we can learn from Rebol?
What we can learn from Rebol?lichtkind
 
Ruby on Rails (RoR) as a back-end processor for Apex
Ruby on Rails (RoR) as a back-end processor for Apex Ruby on Rails (RoR) as a back-end processor for Apex
Ruby on Rails (RoR) as a back-end processor for Apex Espen Brækken
 
Compiler Construction | Lecture 6 | Introduction to Static Analysis
Compiler Construction | Lecture 6 | Introduction to Static AnalysisCompiler Construction | Lecture 6 | Introduction to Static Analysis
Compiler Construction | Lecture 6 | Introduction to Static AnalysisEelco Visser
 
Introduction to Google's Go programming language
Introduction to Google's Go programming languageIntroduction to Google's Go programming language
Introduction to Google's Go programming languageMario Castro Contreras
 
02-chapter-1.ppt
02-chapter-1.ppt02-chapter-1.ppt
02-chapter-1.pptJoel Manio
 

Semelhante a Лев Валкин — Программируем функционально (20)

Erlang Message Passing Concurrency, For The Win
Erlang  Message  Passing  Concurrency,  For  The  WinErlang  Message  Passing  Concurrency,  For  The  Win
Erlang Message Passing Concurrency, For The Win
 
Stay fresh
Stay freshStay fresh
Stay fresh
 
code4lib 2011 preconference: What's New in Solr (since 1.4.1)
code4lib 2011 preconference: What's New in Solr (since 1.4.1)code4lib 2011 preconference: What's New in Solr (since 1.4.1)
code4lib 2011 preconference: What's New in Solr (since 1.4.1)
 
Erlang, an overview
Erlang, an overviewErlang, an overview
Erlang, an overview
 
Programming in Computational Biology
Programming in Computational BiologyProgramming in Computational Biology
Programming in Computational Biology
 
Create Your Own Language
Create Your Own LanguageCreate Your Own Language
Create Your Own Language
 
Ruby on Rails (RoR) as a back-end processor for Apex
Ruby on Rails (RoR) as a back-end processor for Apex Ruby on Rails (RoR) as a back-end processor for Apex
Ruby on Rails (RoR) as a back-end processor for Apex
 
Introduction to Haskell: 2011-04-13
Introduction to Haskell: 2011-04-13Introduction to Haskell: 2011-04-13
Introduction to Haskell: 2011-04-13
 
Scala - The Simple Parts, SFScala presentation
Scala - The Simple Parts, SFScala presentationScala - The Simple Parts, SFScala presentation
Scala - The Simple Parts, SFScala presentation
 
ABRIDGED VERSION - Joys & frustrations of putting 34,000 lines of Haskell in...
 ABRIDGED VERSION - Joys & frustrations of putting 34,000 lines of Haskell in... ABRIDGED VERSION - Joys & frustrations of putting 34,000 lines of Haskell in...
ABRIDGED VERSION - Joys & frustrations of putting 34,000 lines of Haskell in...
 
Erlang kickstart
Erlang kickstartErlang kickstart
Erlang kickstart
 
BayFP: Concurrent and Multicore Haskell
BayFP: Concurrent and Multicore HaskellBayFP: Concurrent and Multicore Haskell
BayFP: Concurrent and Multicore Haskell
 
Hadoop for sysadmins
Hadoop for sysadminsHadoop for sysadmins
Hadoop for sysadmins
 
Managing large datasets in R – ff examples and concepts
Managing large datasets in R – ff examples and conceptsManaging large datasets in R – ff examples and concepts
Managing large datasets in R – ff examples and concepts
 
Scala Talk at FOSDEM 2009
Scala Talk at FOSDEM 2009Scala Talk at FOSDEM 2009
Scala Talk at FOSDEM 2009
 
What we can learn from Rebol?
What we can learn from Rebol?What we can learn from Rebol?
What we can learn from Rebol?
 
Ruby on Rails (RoR) as a back-end processor for Apex
Ruby on Rails (RoR) as a back-end processor for Apex Ruby on Rails (RoR) as a back-end processor for Apex
Ruby on Rails (RoR) as a back-end processor for Apex
 
Compiler Construction | Lecture 6 | Introduction to Static Analysis
Compiler Construction | Lecture 6 | Introduction to Static AnalysisCompiler Construction | Lecture 6 | Introduction to Static Analysis
Compiler Construction | Lecture 6 | Introduction to Static Analysis
 
Introduction to Google's Go programming language
Introduction to Google's Go programming languageIntroduction to Google's Go programming language
Introduction to Google's Go programming language
 
02-chapter-1.ppt
02-chapter-1.ppt02-chapter-1.ppt
02-chapter-1.ppt
 

Último

Histor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slideHistor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slidevu2urc
 
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdfThe Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdfEnterprise Knowledge
 
Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...
Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...
Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...HostedbyConfluent
 
Data Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonData Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonAnna Loughnan Colquhoun
 
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationFrom Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationSafe Software
 
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...Igalia
 
🐬 The future of MySQL is Postgres 🐘
🐬  The future of MySQL is Postgres   🐘🐬  The future of MySQL is Postgres   🐘
🐬 The future of MySQL is Postgres 🐘RTylerCroy
 
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking MenDelhi Call girls
 
Boost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityBoost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityPrincipled Technologies
 
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...Neo4j
 
IAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsIAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsEnterprise Knowledge
 
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Drew Madelung
 
08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking MenDelhi Call girls
 
A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024Results
 
My Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 PresentationMy Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 PresentationRidwan Fadjar
 
Swan(sea) Song – personal research during my six years at Swansea ... and bey...
Swan(sea) Song – personal research during my six years at Swansea ... and bey...Swan(sea) Song – personal research during my six years at Swansea ... and bey...
Swan(sea) Song – personal research during my six years at Swansea ... and bey...Alan Dix
 
Unblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen FramesUnblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen FramesSinan KOZAK
 
A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)Gabriella Davis
 
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhi
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | DelhiFULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhi
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhisoniya singh
 
Breaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path MountBreaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path MountPuma Security, LLC
 

Último (20)

Histor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slideHistor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slide
 
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdfThe Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
 
Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...
Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...
Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...
 
Data Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonData Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt Robison
 
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationFrom Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
 
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
 
🐬 The future of MySQL is Postgres 🐘
🐬  The future of MySQL is Postgres   🐘🐬  The future of MySQL is Postgres   🐘
🐬 The future of MySQL is Postgres 🐘
 
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
 
Boost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityBoost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivity
 
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
 
IAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsIAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI Solutions
 
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
 
08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men
 
A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024
 
My Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 PresentationMy Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 Presentation
 
Swan(sea) Song – personal research during my six years at Swansea ... and bey...
Swan(sea) Song – personal research during my six years at Swansea ... and bey...Swan(sea) Song – personal research during my six years at Swansea ... and bey...
Swan(sea) Song – personal research during my six years at Swansea ... and bey...
 
Unblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen FramesUnblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen Frames
 
A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)
 
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhi
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | DelhiFULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhi
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhi
 
Breaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path MountBreaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path Mount
 

Лев Валкин — Программируем функционально

  • 1. Learning FP Lev Walkin @levwalkin
  • 2. Myself Founder, Chief Editor of a peer-reviewed «Practice of Functional Programming» journal http://fprog.ru/ CTO Echo, a venture backed company http://aboutecho.com/ Proficient in N languages, M of them FP
  • 3. Echo 50,000+ HTTP requests per second 500,000+ simultaneous users on site 1,527,721,774 search queries last month JavaScript, Clojure, Haskell, C, LAMP, RoR, OCaml, Python, Perl, Visual Basic, C++
  • 4. What’s your reason to learn FP? 1. You already suspect that FP approach works best for your domain 2. You want to learn FP to expand your tool set
  • 5. Mature options Haskell (OCaml, F#) Scala Clojure (CL, Scheme) Erlang
  • 6. Statically typed Haskell, OCaml, F# — part of ML family Utilize Hindley—Milner type inference You might not even SEE any types Types provide useful documentation
  • 7. Statically typed Scala Very sophisticated type system Type inference fails often (you have to annotate with types) Lots of syntax sugar, lots of ways to do things
  • 8. Type inference -- Haskell program main = print “Hello, world!” (* OCaml program *) let main = print_string “Hello, world!”
  • 9. Explicit types -- Haskell program main :: IO () main = print “Hello, world!” (* OCaml program *) val main : unit let main = print_string “Hello, world!”
  • 10. Dynamically typed LISP (type annotations are NOT static types) Erlang (Dialyzer helps a bit)
  • 11. Pure FP training ...requires pure language. Haskell is the only viable option.
  • 12. Purity in Haskell Function have no side effects All state changes are only through specially constructed monads (IO, ST) Static types force isolation Lazyness thrown in for a deeper fun
  • 13. Haskell Medium-size syntax, relatively easy to learn, but... Simple & interesting things are EASY Yet, there are LOTS of abstractions and approaches to learn: Type classes, Monads, Arrows, parsing, pretty-printing. This is why we chose Haskell, right?
  • 14. “One” “silly” “example.”
  • 15. Haskell, OCaml, F# data Tree a = ! Leaf a ! | Node (Tree a) (Tree a) type ‘a tree = ! | Leaf of ‘a ! | Node of ‘a tree * ‘a tree type Tree<'a> = | Leaf of ‘a | Branch of ‘a Tree * ‘a Tree http://fprog.ru/2009/issue2/roman-dushkin-algebraic-data-types/
  • 16. “One” 3 “silly” “example.” 5 8
  • 17. Haskell data Tree String = ! Leaf String ! | Node (Tree String) (Tree String) strToLenTree :: Tree String ! Tree Int strToLenTree (Leaf s) = Leaf (length s) strToLenTree (Node left right) = ! ! ! Node (strToLenTree left) ! ! ! ! ! (strToLenTree right)
  • 18. Haskell data Tree a = ! Leaf a ! | Node (Tree a) (Tree a) mapTree :: (a ! b) ! Tree a ! Tree b mapTree f (Leaf x) = Leaf (f x) mapTree f (Node left right) = ! ! ! ! Node (mapTree f left) ! ! ! ! ! ! (mapTree f right) strToLenTree :: Tree String ! Tree Int strToLenTree = mapTree length
  • 19. Prototyping [~]> ghci tree.hs GHCi, version 7.0.4 :? for help [1 of 1] Compiling Main ( tree.hs, interpreted ) Ok, modules loaded: Main. *Main> let tree = Node (Leaf "An") (Leaf "example") *Main> mapTree (s -> length s) tree Node (Leaf 2) (Leaf 7) *Main> mapTree (s -> filter Data.Char.isUpper s) tree Node (Leaf "A") (Leaf "") *Main> mapTree (filter Data.Char.isLower) tree Node (Leaf "n") (Leaf "example") *Main> :t mapTree mapTree :: (a -> b) -> Tree a -> Tree b *Main> :t mapTree length mapTree length :: Tree [a] -> Tree Int
  • 20. LISP Clojure: immutability, persistent data structures, JVM Scheme: very small language, suitable for teaching/learning Common Lisp: it is a fat multiparadigm language and has everything (though parts may be rotten a bit)
  • 21. Erlang Simple language Telecom systems, 24/7, системы массового обслуживания (web?) Hot code reload, deep introspection, embedded facilities for easier clustering
  • 22. Erlang % Reverse a string reverse(String) -> reverse2(String, []). % Reverse with an accumulator reverse2([ ], Acc) -> Acc; reverse2([Head | Tail], Acc) -> ! reverse2(Tail, [Head | Acc]).
  • 23. Erlang % Sends request to the [remote] system % and waits for the response back send_and_wait(Pid, Message, Timeout) -> ! Pid ! Message, ! receive ! ! Response -> {ok, Response} ! after ! ! Timeout -> {error, timeout} ! end.
  • 24. Clojure vs LISP* NEW language, with sound idioms Immutable data structures are idiomatic Fast pace of development JVM may be a big bon for some Learn it if you want sound, practical language http://tonsky.livejournal.com/tag/clojure
  • 25. Scheme vs LISP* Small, simple language (R5RS) A basis for SICP — Structure and Interpretation of Computer Programs Learn SICP if you want to study Programming
  • 26. CL vs LISP* Many complex ideas mixed in No enforcement of a good style — you have to do it on your own Learn it if you want unrestricted power
  • 27. Haskell vs ML* More sound type system LOTS of language research happen on Haskell Learn it if you want to learn FP Learn it if it fits your domain well http://www.ozon.ru/context/detail/id/8696277/
  • 28. OCaml Several mostly compatible syntaxes You can always create a mutable variable or class field, though not idiomatic Clearer semantics and computation model (straightforward translation to assembly) http://mirror.ocamlcore.org/ocaml-tutorial.org/the_basics.html
  • 29. OCaml vs ML* OCaml is to Haskell as C is to C++ Poor library support FAST (on 1-core systems) Learn it if you want a practical tool and not satisfied with Haskell or F# http://www.slideshare.net/michielovereem/beyond-functional- programming-in-haskell-an-introduction-to-ocaml
  • 30. F# vs ML* Works under Microsoft .Net F# on Mono is somewhat usable Learn it if you want to tinker with FP on MS platform http://www.ozon.ru/context/detail/id/6151130/
  • 31. Erlang vs * SMALL language, somewhat bigger OTP Great support for concurrency (Actors), and parallelism Hot code reload & run time introspection OOP on the outside; FP on the inside Learn it if you build 24/7 production system
  • 32. Scala vs * Big language, a functional C++ of sorts JVM Learn it if you want a great tool, not satisfied with Java, yet have no appreciation for true elegance (Clojure)
  • 33. Learning FP Haskell provides models and abstractions (read papers) — pure FP Scheme teaches you Programming (read SICP) Everything else is too practical
  • 34. Practicing FP .Net → F# JVM → Clojure (elegance and simplicity), Scala (less restrictions) !{.Net|JVM} → OCaml (if you do not need libraries), Clojure, Haskell (if you have balls) 24/7 → Erlang
  • 35. For individuals You want flexible system which allows you to cut corners Common Lisp Scala F#
  • 36. For teams You want to think about lifecycle, support, maintenance, group dynamics OCaml (static typing provides some guarantees) Erlang (simple and straightforward, designed to withstand errors, good for novices)
  • 37. For teams Scala gets increasingly popular because people do not appreciate elegance and sound restrictions People will throw up in a few years working with accumulated Scala code ...like C++ http://ru.xored.com/2012/12/02/scala/
  • 38. Haskell resources Мягкое введение в Haskell Изучай Haskell во имя добра! http://www.rsdn.ru/article/haskell/haskell_part1.xml
  • 39. Clojure resources 1. Learn spoken English 2. Журнал Никиты Прокопова (tonsky@LJ) содержит ссылки и рекомендации http://tonsky.livejournal.com/tag/clojure
  • 40. Erlang resources 1. Programming Erlang: Software for a Concurrent World 2. http://learnyousomeerlang.com http://www.ozon.ru/context/detail/id/3645143/
  • 42. Thank you! Questions? @levwalkin