Functional Programming Patterns
slideshare.net
slideshare.net
Usually this is achieved by representing the pattern exactly in the language. Usually the patterns are just maths. Usually math happily quantifies over higher-kinded types. Thus, you really want HKTs in your language.
And to be fair, Haskell does not go tremendously far in this direction. The languages which will truly profit from this are still in gestation.
What are examples of taking it further?
In a DT language you have something called a Pi type which is a bit like a function type. An example would be to compare the types of two functions which, essentially, determine whether two integers are coprime
coprime1 : Int -> Int -> Bool
coprime2 : (a : Int) -> (b : Int) -> Maybe (IsCoPrime a b)
The important part is to look past the syntax and note that IsCoPrime is a type which depends upon the values of the first two arguments. Another way of reading this is as follows coprime3 : forall (a b : Int), Maybe (IsCoPrime a b)
this emphasizes that the type of `coprime3` is quantifying over all values in Int.Then we can take this idea to the higher-kinded level by looking at the type of, say, monoids
monoid : forall (A : Type),
{ zero : A
, plus : A -> A -> A
, leftId : forall (a : A), plus zero a = a
, rightId : forall (a : A), plus a zero = a
, assoc : forall (a b c : A) , plus a (plus b c) =
plus (plus a b) c
}
Here we can see that the `forall` notation lets us freely abstract over "all types" just like we previously abstracted over "all values". This continues to work at every level. For instance, we can note that `monoid` above is "a type of types" or maybe a "specification" and we can abstract over all "all specifications" as well specProperty : forall (S : Type -> Type), P SOne of the things I'm always thinking when people talk about the merits of various type systems and the problems they solve is: "But I don't have those problems". However, there are a few good examples in there that opened my eyes a little and I'll give type-centric programming a go on my next project. Not necessarily solving problems that I have, but certainly presenting a different, hopefully clearer, way of writing some functionality.
Writing Scala in my day job currently (which, for the most part, I quite enjoy) but can see jumping ship if Microsoft's move to Linux is successful. Being able to develop and deploy F# applications on Linux with full blown Type Providers and decent IDE support? Pretty compelling combo, and that's just the tip of the iceberg.
Of course, I far far far prefer Linux in general terms, but the MS tooling is quite decent. eg. I still haven't found anything that even begins to compare to the MSSQL management studio.
It is being adopted in European financial and insurance sectors for data modelling.
You will need the Silverlight plugin.
The comparison between Slides 81 and 82 is particularly unfair because the "object soup" actually does deal with the database, SMTP, and so on and the functional version doesn't. If you add those in, you're going to get something complicated: perhaps a bunch of monad transformers or some such?
Slide 104 is misleading. In an imperative language, you can write a decorator function that logs a function's inputs and outputs, and it will have the same API. In a pure language, you can't do that because a function that does I/O has a different type. The flexibility or sloppiness (depending on your point of view) that allows you to do I/O anywhere is really a feature of imperative languages rather than pure functional languages.
> The comparison between Slides 81 and 82 is particularly unfair because the "object soup" actually does deal with the database, SMTP, and so on and the functional version doesn't. If you add those in, you're going to get something complicated: perhaps a bunch of monad transformers or some such?
You clearly need state somewhere (something needs to be able to reach the connection pool), so, yes, the comparison is unfair.
The part about functors/monads/monoids is also nice, although I feel like it would be better with the accompanying talk to bind it together a bit more.
Seriously, it gives off the impression not that these are going to be better patterns. But that someone simply has a bias against "patterns" as they are promoted in Java and then rails against it saying that they are going back to the root of the word patterns. Ignoring that this is the same path.
"Functional Programming in Scala" is also well worth a read as well if you're trying to learn FP... I've found it to be excellent, especially since it has lots of exercises to use for practice.
I am wondering if there are any other good resources for teaching the functional programming paradigms. Anybody care to recommend me some resources?
Also, I mainly work with Ruby and Javascript in my full time job. Currently, in school, I use Java (in the context of Android, which is on Java 6) and Objective-C (iOS programming). If anybody has any resources regarding functional programming and the previously mentioned languages, it would be most appreciated.
Thanks people!
Also, I have been blogging a lot about functional programming in javascript with practical code examples http://bahmutov.calepin.co/tag/functional.html
In particular how to go from imperative style to functional to reactive in JavaScript http://bahmutov.calepin.co/journey-from-procedural-to-reacti...
The lectures are basically laid out 1:1 with Hutton's Programming in Haskell book, so if you're familiar with that book, you're familiar with the way the course is structured. I find the actual experience of doing all the homework questions very helpful, even if so far nothing has been particularly difficult.
Be aware it starts out really slow then 50% in ratchets up the fun into "scare away the freshman" territory with monads. I have to say preexisting knowledge has been quite helpful.
About my only complaint is the amount of "which of these 9 implementations are valid" exercises. Although i've been cheating and using hspec to tdd my way through them.
But is there, except for Clojurescript, any true (like Haskell) FP language for browsers? Something that has the tools, and community to back it, so it's viable to actually make projects in it?
- https://github.com/faylang/fay
- https://github.com/ghcjs/ghcjs
Each has it's own focus and strengths and weaknesses.
There is a long page on the Haskell wiki on the subject: https://www.haskell.org/haskellwiki/The_JavaScript_Problem
Michael Snoyman gave a really good talk recently which covers GHCJS and Fay: https://www.youtube.com/watch?v=XfINRj5OzGw
Eg: slide 64 encourages the reader to "Using sum vs inheritance", and then goes on to show the "good" algebraic datatypes (no behaviour, just data) vs the "bad"... multiple class implementing the same interface (which I wouldn't call inheritance).
I did not however continue to use haskell since it doesnt have key libraries I need.
I instead adopted livescript,underscore into javascript and was good to go.
With linear algebra the library HMatrix is broken in more than one place, it also requires me to learn a lot of new types just to do simple matrix decomposition.
Regular expression in haskell requires me to learn a completely new way to do them, I am not under the impression that regular expression is broken in any way in python or javascript that it requires new syntax.
Haskell also does not have access to the browser runtime which is key if you are want maximum exposure for your work - ( no one is interested in binaries anymore ).
There is purescript but its a large layer over javascript and even a simple hello world results in a 2000 LOC compilation of javascript.
I am not a computer programmer, I am an applied Mathematician and haskell requires a lot of work before it can be used for serious work the type of work I do.
Haskell doesnt have the use of use that is offered by things like npm, browserify which are the most awesome tools I have used.
This really depends on which compilation route you take. `psc-make` will include all of the Prelude and compile to CommonJS modules, which can result in quite a bit of code, but `psc` will trim out all unused functions, and should result in about 10 LOC for Hello World.
What was broken about HMatrix? What library has the best API to you? Algebra[0] from Node?
var algebra = require('algebra');
var M = algebra.MatrixSpace;
var R = algebra.Real;
// Create the space of 2x2 real matrices
var R2x2 = new M(R, 2);
// Create two invertible matrices:
//
// | 1 2 | | -1 0 |
// | 3 4 | and | 0 1 |
//
var m1 = new R2x2.Matrix([1, 2,
3, 4]);
var m2 = new R2x2.Matrix([-1, 0,
0, 1]);
// Multiply m1 by m2 at right side
// | 1 2 | * | -1 0 | = | -1 2 |
// | 3 4 | | 0 1 | | -3 4 |
m1.mul(m2);
console.log(m1.data); // [-1, 2, -3, 4]
// Check out m1 determinant, should be 2 = (-1) * 4 - (-3) * 2
console.log(m1.determinant.data); // 2
> Regular expression in haskell requires me to learn a completely new way to do them, I am not under the impression that regular expression is broken in any way in python or javascript that it requires new syntax.What new syntax? I'm not sure what you mean by "learn a completely new way to do them".
Haskell (pcre-light[1]):
> import Text.Regex.PCRE.Light
> let numberRgx = compile "[0-9]+" []
> match numberRgx "the answer is 42" []
Just ["42"]
Node:/[0-9]+/g.exec("the answer is 42")[0];
Haskell (regex-tdfa[2]):
> import Text.Regex.TDFA > "the answer is 42" =~ "[0-9]+" :: String "42"
Ahh, I think I see what you mean now. You want the familiar /regex/string syntax right? There used to be a QuasiQuoter (template haskell library) that allowed syntax like:
ghci> [$rx|[0-9]+|] "the answer is 42"
Just ["42"]
However it[3] seems to have bitrotted and everyone else is using the "needle" =~ "match" syntax.EDIT: Found a useful website comparing language implementations, namely regex in perl vs Haskell:
http://langref.org/haskell+perl/pattern-matching
0: http://g14n.info/algebra/examples/quick-start
1: http://hackage.haskell.org/package/pcre-light
2: http://hackage.haskell.org/package/regex-tdfa
3: http://hackage.haskell.org/package/regexqq (bitrotted)
Things like this are literally why I switched from Python to Racket almost immediately once I discovered the latter. So much time spent fighting an imperative language to do something that seemed like it should just be easier in the first place.
I am also unconvinced that the imperative nature of many languages is the problem. Not sure what it is.
I think tel is mostly on the right track of what I mean when I compare Racket to traditional ALGOL languages, but it is also true to say that Racket is not strictly non-imperative either: it is ultimately a multi-paradigm language, just one that culturally leans harder towards a functional-declarative style. My early projects were just as lousy with mutable state and in-order processing as anything I wrote in Python; but I got better.
I think what really drove me to Lisp and FP languages was the notion of nearly everything being first-class values, from functions to objects, and it's this quality, compared to the tedium of building yet another !"¤&¤&! constructor pattern that really attracted me. This, plus things like macros, the way the language allows for function composition so readily, is what made Lisp feel like 'how programming should've been all along' for me. Haskell as well induced that same reaction in other ways (mmm ... curry ...), though I'm still not entirely convinced that such strict purity is practical.
And I like currying and such, as well. Even use it in Racket quote often. Isn't too uncommon to see something like in my projects.
((compose
(curry func1 val1)
func2
func3) seed)
I think what really makes Racket so amazing to me is just how easy it is to iteratively write a function. Start with a core, and gradually append around it more and more till it is done. Testing with values throughout the whole process.I also like the literature around Lisp. Land of Lisp and SICP are both very well written and just plain fun to read.
Today I wrote a struct system in 29 lines of code. Kinda hard sometimes to do that and then even think about going back to, well, much of anything but another Lisp or composable FP language, really.
I was actively avoiding the obviously imperative functions, though. Not sure why. That is, I could have simply said that the existence of all of the functions that end in exclamation points shows the language is imperative.
(define x 3)
(display x)
(set! x (add1 x))
(display x)
is about as imperative as they come, by my definition. And not a begin in site. (let* ((a 1) (b a))
(+ a b))
is an abbreviation for (let ((a 1))
(let ((b a))
(+ a b))))
which, in turn, is a syntactic sugar for ((lambda (a)
((lambda (b)
(+ a b)) a)) 1)
There is no "assignment", only lexicaly scooped bindings, which are "stateless" and "declarative".Looping constructs in Racket are just syntactic sugar - layered macros, based on what they call "contracts", I suppose.
In CL looping constructs are micro-DSLs.
Simply put, functional is not necessarily the opposite of imperative.
I took to googling to see if someone had made my point better already. The best I found quickly is this[1]. It is a good read. As it points out that we are most likely both stuck on different numbers in the "opposite of imperative" definition world.
I will say that throwing out mutability with the bathwater is perhaps the single most frustrating thing with most functional advocacy.
[1] https://existentialtype.wordpress.com/2013/07/18/what-if-any...
It also carries the best explanation for why one would want to use monads that I've seen.