News for hackers. Stuff that matters.
Re:How to stop functional programming by the_af on Tuesday February 23, 2016 @09:48AM (#11159150)
I've had some success explaining, mainly through pair programming, code reviews and an educational use of the console, the basics of FP-ish constructs such as map, fold, filter, pattern matching, control of side-effects, etc.

It's amazing what you can do if, instead of assuming an arrogant attitude, you take your time to teach other programmers and review their code to explain how to avoid pitfalls, and accept that some people will remain unconvinced about some aspects of FP that you cannot adequately justify (a good reason to seek a better understanding of those justifications!). And it has the added benefit that this situation will never reach your manager, so he/she doesn't have to get involved :)

Re:How to stop functional programming by sundarurfriend on Tuesday February 23, 2016 @10:07AM (#11159321)
> such as map, fold, filter, pattern matching, control of side-effects, etc.

map and filter have become natural parts of my thinking, fold too is getting there, and avoidance of side-effects even gives pleasant tingles to the math-guy in me, but I've never understood what pattern matching brings to the table. In my admitted limited understanding, they seem to be a syntactic sugar for if-elseif branching that ends up scattering the logic of a function to multiple blocks of code, while bringing no obvious benefit compared to them.

Since you mentioned your success explaining the justifications for these things, I thought I'd take advantage of that here. :) Could you explain what I'm missing with pattern matching?

Re:How to stop functional programming by kinghajj on Tuesday February 23, 2016 @10:23AM (#11159459)
Pattern matching is not just sugar for an if-elseif chain, since compilers will check for exhaustiveness. This is especially important when used with sum types (which are the primary motivator for this feature):

    data Thing
      = Foo String
      | Bar Int Double
      | Baz String String

    case thing of
      Foo s -> putStrLn s
      Bar i f -> -- ...
      Baz s1 s2 -> -- ...
If you later add another variant to Thing, the compiler will check that all pattern matches against it account for the new case. (Wildcard matches alleviate the need always to handle every case.) An if-elseif chain, however, would still compile after adding the new variant, so you must track down the usages manually.
Re:How to stop functional programming by Cthulhu_ on Tuesday February 23, 2016 @10:28AM (#11159503)
Aha, thanks for that bit, I didn't realize that. I thought Swift, which has a switch/case statement that does not have automatic fallthrough and which has to be exhaustive, was special in that regard. (Although in Swift you can in most cases just do a 'default' case too, not sure how that works with pattern matching)
Re:How to stop functional programming by lmm on Tuesday February 23, 2016 @11:34AM (#11160049)
This is why functional programmers get so grouchy - it's great that Swift has picked up this kind of functionality, but ML family languages have had it for 40 years now :/. Worse is when a feature gets dismissed as "incomprehensible" for years until it gets picked up by some fashionable language and then suddenly everyone's excited about it.
Re:How to stop functional programming by jnbiche on Tuesday February 23, 2016 @11:43AM (#11160144)
Pattern matching is awesome, and ML definitely gets the credit here for putting it into practice, but matching is arguably not even part of the functional paradigm. Lots of non-functional languages could greatly benefit from pattern matching and sum types.

And indeed, when you look at a language like Nim and Swift, that's exactly what happened. Rust, too, although Rust is arguably a functional language.

Re:How to stop functional programming by AnimalMuppet on Tuesday February 23, 2016 @12:18PM (#11160460)
Rust is arguably a functional language? I'd love to hear the argument that says that it is...
Re:How to stop functional programming by jnbiche on Tuesday February 23, 2016 @12:35PM (#11160605)
> I'd love to hear the argument that says that it is...

http://science.raphael.poss.name/rust-for-functional-program...

I personally think Rust isn't functional, but rather multi-paradigm with a strong functional influence. But if you were to add TCO and a few other features, I think Rust would be a full-blown functional language, so it may get there yet.

In any case, it's useless arguing over (should have known better than say anything), so this will be my last word on the issue.

Re:How to stop functional programming by AnimalMuppet on Tuesday February 23, 2016 @12:41PM (#11160665)
I wasn't actually looking to argue; I was looking to understand.

And I guess it's going to come down to "whose definition of FP are we using?" If FP means "I can write in a functional style", there are many more functional languages than if FP means "I can only write in a functional style". That debate - about whose definition of FP is correct - is one that I can't bother to care very much about.

Re:How to stop functional programming by lmm on Tuesday February 23, 2016 @12:21PM (#11160489)
The term "functional" today more-or-less means "a language like Haskell and the ML family" (I know this is not the original meaning), which Rust is.
Re:How to stop functional programming by AnimalMuppet on Tuesday February 23, 2016 @12:43PM (#11160681)
I'm still trying to understand (not argue). How is Rust like Haskell and the ML family? My impression of Rust is that it's like C++ but with clear tracking of who owns what memory.

[Edit: I see that the link from jnbiche is probably going to answer my question, though it's going to take me a while to digest it...]

Re:How to stop functional programming by lmm on Tuesday February 23, 2016 @05:49PM (#11163003)
It's immutable by default, with mutation only when managed (most famously a Haskell thing). It has a rich type system with ADTs and generics but without subtyping (very much the ML/Haskell tradition). It distinguishes between validation-like failures and system-level errors, handling the former with values and the latter with panics (i.e. noncaught exceptions) - Erlang is the most famous example of this style, but it's common in Haskell and ML too. It tries to push functionality into libraries rather than the core language - it seems to care about having sensible, consistent semantics rather than ad-hoc.
Re:How to stop functional programming by sanderjd on Tuesday February 23, 2016 @01:53PM (#11161288)
It really depends on what you think are the features of Haskell that typify its "family". If you think it's typified by things like type inference, sum types, and typeclasses, then Rust will feel very Haskell-y, but if you think it's typified by higher kinded types, laziness, and functional purity, then it won't feel very Haskell-y at all.

Personally, I think Haskell and C++ are the two biggest influences I feel when using Rust: it has a lot of Haskell's philosophy around data types and polymorphism, and a lot of C++'s philosophy around the life cycle of resources, and the cost of abstractions.

Re:How to stop functional programming by AnimalMuppet on Tuesday February 23, 2016 @03:41PM (#11162145)
I think the life cycle of resources issue was a big reason why I was surprised to hear people say that Rust was Haskell-like.
Re:How to stop functional programming by steveklabnik on Tuesday February 23, 2016 @02:08PM (#11161433)
I'm in the "no" camp, personally, but we _did_ inherit a lot of things from OCaml. The initial compiler was written in it, a lot of the syntax and features are inspired by it, and it just _feels_ more ML than Haskell.

Rust may not be a functional language, but it draws heavy inspiration from them.

Re:How to stop functional programming by Jtsummers on Tuesday February 23, 2016 @12:21PM (#11160491)
In other languages with pattern matching you often have some sort of wildcard that you can match against. Either an explicitly named variable or, commonly, an underscore (`_`) if the value is unused. Example in erlang:

  foo(bar) -> baz;
  foo(X)   -> bang.
The X is an explicit variable that will match anything not already matched in previous patterns. It can also be used. (NB: Erlang pattern matching is the same or essentially the same for this discussion at each possible level, whether in a function declaration as above or a case statement or when receiving messages.)

Here, we don't care about the thing we've named with an underscore:

  tail([_|Tail]) -> Tail.
In Erlang, `[1|[2,3]]` is equivalent to the list `[1,2,3]`. So `[H|T]` as a pattern would have `H = 1` and `T = [2,3]`. Since we don't care about the head of the list, we name it with _. Optionally, in Erlang, you can give it a fuller name:

  tail([_Head|Tail]) -> Tail.
The compiler knows that _Head is supposed to be unused and won't complain (warning about unused variables).

  tail([Head|Tail]) -> Tail.
Would give a warning.
Re:How to stop functional programming by ffriend on Tuesday February 23, 2016 @11:28AM (#11159996)
True in Haskell, but not e.g. in Scala. In Scala, pattern matching is done using partial functions that are defined only for certain patterns. E.g. it's totally legal to write:

  obj match {
    case Foo(x) => ...
    case Bar(y, z) => ...
    // no Baz here
  }
Re:How to stop functional programming by sampo on Tuesday February 23, 2016 @12:41PM (#11160662)
In Scala you get the compiler to check for exhaustive pattern matching if you use case classes and sealed classes. So if you want exhaustiveness checks, you can have them.
Re:How to stop functional programming by logicfiction on Wednesday February 24, 2016 @11:30AM (#11167955)
Not entirely true. You would get a warning if its not exhaustive matching for a sealed trait and you can make warnings into compiler errors with a compiler flag.
Re:How to stop functional programming by akavi on Tuesday February 23, 2016 @11:11AM (#11159846)
> since compilers will check for exhaustiveness.

That's not really required for pattern matching. Certainly makes it more useful, and most implementations have it, however.

Re:How to stop functional programming by jarcane on Tuesday February 23, 2016 @10:35AM (#11159561)
Pattern matching isn't just conditional matching. It's also binding, and even some common operations. Compare a naive Haskell map:

  map f   []   = []
  map f (x:xs) = f x : map f xs
To a Racket one made without using (match...):

  (define (map f lst)
    (cond
      [(empty? lst) '()]
      [else (cons (f (car lst))
                  (map f (cdr lst)))]))
The former is far more terse, and also more directly resembles a definition of what map actually does. The latter is wordy, because all kinds of things have to be stated in explicit terms, and operations need to be performed manually instead of with simple destructuring binds.

This is a mild example too, it gets far, far more useful when you're dealing with type/struct fields and the like.

Re:How to stop functional programming by jnbiche on Tuesday February 23, 2016 @11:34AM (#11160057)
Just curious why you would use that imperative example with Racket, and not an imperative language like Python, or even Haskell? You parenthetically mention (match) (ha!) but to someone who doesn't know the languages, give the impression that Racket can't do pattern matching.

Anyway, this is the analogous `map` in racket:

    (define (my-map f lst)
      (match lst
        ['()            '()]
        [(cons hd tl)    (cons (f hd) (my-map f tl))]))
It's a 1-to-1 correspondence, and is arguably the idiomatic way to define `map` in Racket.
Re:How to stop functional programming by jarcane on Tuesday February 23, 2016 @05:05PM (#11162731)
I was largely using Racket as a common enough Scheme that I have installed my computer. I wanted an example from another functional language but in an older classical style (I was shooting for the Little Schemer here). I'm quite familiar with Racket's match, somewhere around my blog I even have a "proof" of sorts of using Racket's match to do the famous Haskell quicksort in just as few lines of code.

If you really want an ugly rendition I could try and replicate one of the awful JavaScript versions of "map" that uses a for loop, but I thought that might obscure the comparison of operations too much, and the semantics wouldn't be equivalent (linked lists vs. JS arrays).

Re:How to stop functional programming by abecedarius on Tuesday February 23, 2016 @11:28AM (#11159999)
That wasn't quite a fair comparison.

    map f xs =
      if empty xs
      then []
      else f (head xs) : map f (tail xs)
(I like pattern matching too.)
Re:How to stop functional programming by jarcane on Tuesday February 23, 2016 @05:06PM (#11162738)
The point isn't to be a "fair" comparison, but rather to compare the number of explicit operations involved. I'd note that your Haskell example there is largely equivalent to the Scheme one.
Re:How to stop functional programming by abecedarius on Tuesday February 23, 2016 @08:49PM (#11163919)
Yes, it's equivalent on purpose. Yet in Haskell it's only a couple tokens longer than the pattern-matching original which you called "far more terse". To fairly test a claim, one should change only the variables the claim is about.
Re:How to stop functional programming by mbucc on Tuesday February 23, 2016 @10:49AM (#11159666)
The benefit I see is that (at least in Erlang) pattern matching combines pre-condition asserts with programming the sunny path. For example,

   "/" ++ X = HttpRequest:get(path).
will crash if PATH_INFO doesn't include leading slash. Writing just the sunny path and getting asserts "for free" (without any clutter) is a fun way to program.

I also find that statement very readable.

BTW, here's some Java code that does the same thing:

  String Path;
  if (HttpRequest.getPathInfo().startsWith("/")) {
     Path = HttpRequest.getPathInfo().substring[1:];
  } else {
     String emsg = "no match of right hand side value \"%s \"";
     throw new IllegalStateException(emsg.format(HttpRequest.getPathInfo());
  }
Re:How to stop functional programming by st3v3r on Tuesday February 23, 2016 @12:51PM (#11160766)
Right, but how do you do that if your coworkers are just as against communication, and decide to go straight to the manager to complain without asking how the code works first?
Re:How to stop functional programming by the_af on Tuesday February 23, 2016 @01:29PM (#11161072)
That's a pretty bad situation, agreed. I think it exceeds the scope of what programming constructs/paradigms to use, and is instead a way more serious problem. With this kind of coworkers, I predict everything is going to be a problem.