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


Published on

Published in: Technology
1 Like
  • Be the first to comment

No Downloads
Total views
On SlideShare
From Embeds
Number of Embeds
Embeds 0
No embeds

No notes for slide

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

  1. 1. Learning FP Lev Walkin @levwalkin
  2. 2. MyselfFounder, Chief Editor of a peer-reviewed«Practice of Functional Programming»journal http://fprog.ru/CTO Echo, a venture backed companyhttp://aboutecho.com/Proficient in N languages, M of them FP
  3. 3. Echo50,000+ HTTP requests per second500,000+ simultaneous users on site1,527,721,774 search queries last monthJavaScript, Clojure, Haskell, C, LAMP, RoR,OCaml, Python, Perl, Visual Basic, C++
  4. 4. What’s your reason to learn FP?1. You already suspect that FP approach works best for your domain2. You want to learn FP to expand your tool set
  5. 5. Mature optionsHaskell (OCaml, F#)ScalaClojure (CL, Scheme)Erlang
  6. 6. Statically typedHaskell, OCaml, F# — part of ML familyUtilize Hindley—Milner type inferenceYou might not even SEE any typesTypes provide useful documentation
  7. 7. Statically typedScalaVery sophisticated type systemType inference fails often (you have toannotate with types)Lots of syntax sugar, lots of ways to dothings
  8. 8. Type inference-- Haskell programmain = print “Hello, world!”(* OCaml program *)let main = print_string “Hello, world!”
  9. 9. Explicit types-- Haskell programmain :: IO ()main = print “Hello, world!”(* OCaml program *)val main : unitlet main = print_string “Hello, world!”
  10. 10. Dynamically typedLISP (type annotations are NOT statictypes)Erlang (Dialyzer helps a bit)
  11. 11. Pure FP training...requires pure language.Haskell is the only viable option.
  12. 12. Purity in HaskellFunction have no side effectsAll state changes are only throughspecially constructed monads (IO, ST)Static types force isolationLazyness thrown in for a deeper fun
  13. 13. HaskellMedium-size syntax, relatively easy tolearn, but...Simple & interesting things are EASYYet, there are LOTS of abstractions andapproaches to learn: Type classes,Monads, Arrows, parsing, pretty-printing.This is why we chose Haskell, right?
  14. 14. “One” “silly” “example.”
  15. 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 treetype Tree<a> = | Leaf of ‘a | Branch of ‘a Tree * ‘a Tree http://fprog.ru/2009/issue2/roman-dushkin-algebraic-data-types/
  16. 16. “One” 3 “silly” “example.” 5 8
  17. 17. Haskelldata Tree String =! Leaf String! | Node (Tree String) (Tree String)strToLenTree :: Tree String ! Tree IntstrToLenTree (Leaf s) = Leaf (length s)strToLenTree (Node left right) =! ! ! Node (strToLenTree left)! ! ! ! ! (strToLenTree right)
  18. 18. Haskelldata Tree a =! Leaf a! | Node (Tree a) (Tree a)mapTree :: (a ! b) ! Tree a ! Tree bmapTree f (Leaf x) = Leaf (f x)mapTree f (Node left right) =! ! ! ! Node (mapTree f left)! ! ! ! ! ! (mapTree f right)strToLenTree :: Tree String ! Tree IntstrToLenTree = mapTree length
  19. 19. Prototyping[~]> ghci tree.hsGHCi, 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) treeNode (Leaf 2) (Leaf 7)*Main> mapTree (s -> filter Data.Char.isUpper s) treeNode (Leaf "A") (Leaf "")*Main> mapTree (filter Data.Char.isLower) treeNode (Leaf "n") (Leaf "example")*Main> :t mapTreemapTree :: (a -> b) -> Tree a -> Tree b*Main> :t mapTree lengthmapTree length :: Tree [a] -> Tree Int
  20. 20. LISPClojure: immutability, persistent datastructures, JVMScheme: very small language, suitable forteaching/learningCommon Lisp: it is a fat multiparadigmlanguage and has everything (thoughparts may be rotten a bit)
  21. 21. ErlangSimple languageTelecom systems, 24/7, системымассового обслуживания (web?)Hot code reload, deep introspection,embedded facilities for easier clustering
  22. 22. Erlang% Reverse a stringreverse(String) -> reverse2(String, []).% Reverse with an accumulatorreverse2([ ], Acc) -> Acc;reverse2([Head | Tail], Acc) ->! reverse2(Tail, [Head | Acc]).
  23. 23. Erlang% Sends request to the [remote] system% and waits for the response backsend_and_wait(Pid, Message, Timeout) ->! Pid ! Message,! receive! ! Response -> {ok, Response}! after! ! Timeout -> {error, timeout}! end.
  24. 24. Clojure vs LISP*NEW language, with sound idiomsImmutable data structures are idiomaticFast pace of developmentJVM may be a big bon for someLearn it if you want sound, practicallanguage http://tonsky.livejournal.com/tag/clojure
  25. 25. Scheme vs LISP*Small, simple language (R5RS)A basis for SICP — Structure andInterpretation of Computer ProgramsLearn SICP if you want to studyProgramming
  26. 26. CL vs LISP*Many complex ideas mixed inNo enforcement of a good style — youhave to do it on your ownLearn it if you want unrestricted power
  27. 27. Haskell vs ML*More sound type systemLOTS of language research happen onHaskellLearn it if you want to learn FPLearn it if it fits your domain well http://www.ozon.ru/context/detail/id/8696277/
  28. 28. OCamlSeveral mostly compatible syntaxesYou can always create a mutable variableor class field, though not idiomaticClearer semantics and computationmodel (straightforward translation toassembly) http://mirror.ocamlcore.org/ocaml-tutorial.org/the_basics.html
  29. 29. OCaml vs ML*OCaml is to Haskell as C is to C++Poor library supportFAST (on 1-core systems)Learn it if you want a practical tool andnot satisfied with Haskell or F# http://www.slideshare.net/michielovereem/beyond-functional- programming-in-haskell-an-introduction-to-ocaml
  30. 30. F# vs ML*Works under Microsoft .NetF# on Mono is somewhat usableLearn it if you want to tinker with FP onMS platform http://www.ozon.ru/context/detail/id/6151130/
  31. 31. Erlang vs *SMALL language, somewhat bigger OTPGreat support for concurrency (Actors),and parallelismHot code reload & run time introspectionOOP on the outside; FP on the insideLearn it if you build 24/7 productionsystem
  32. 32. Scala vs *Big language, a functional C++ of sortsJVMLearn it if you want a great tool, notsatisfied with Java, yet have noappreciation for true elegance (Clojure)
  33. 33. Learning FPHaskell provides models and abstractions(read papers) — pure FPScheme teaches you Programming (readSICP)Everything else is too practical
  34. 34. Practicing FP.Net → F#JVM → Clojure (elegance and simplicity),Scala (less restrictions)!{.Net|JVM} → OCaml (if you do not needlibraries), Clojure, Haskell (if you haveballs)24/7 → Erlang
  35. 35. For individualsYou want flexible system which allowsyou to cut cornersCommon LispScalaF#
  36. 36. For teamsYou want to think about lifecycle,support, maintenance, group dynamicsOCaml (static typing provides someguarantees)Erlang (simple and straightforward,designed to withstand errors, good fornovices)
  37. 37. For teamsScala gets increasingly popular becausepeople do not appreciate elegance andsound restrictionsPeople will throw up in a few yearsworking with accumulated Scala code...like C++ http://ru.xored.com/2012/12/02/scala/
  38. 38. Haskell resourcesМягкое введение в HaskellИзучай Haskell во имя добра! http://www.rsdn.ru/article/haskell/haskell_part1.xml
  39. 39. Clojure resources1. Learn spoken English2. Журнал Никиты Прокопова (tonsky@LJ) содержит ссылки и рекомендации http://tonsky.livejournal.com/tag/clojure
  40. 40. Erlang resources1. Programming Erlang: Software for a Concurrent World2. http://learnyousomeerlang.com http://www.ozon.ru/context/detail/id/3645143/
  41. 41. Shameless plugЖурнал «Практикафункциональногопрограммирования»fprog.ru@fprogru
  42. 42. Thank you!Questions? @levwalkin