by tsahyt · 14y ago · 0 comments
I agree, functional programming is great but sometimes I just see ideas being sold as "functional" that apply to programming in general. Splitting programs into smaller parts that are easily solvable and work in a predictable way is one of the most fundamental parts of coding.
Sure, that's not all there is to it, but I'm a little bothered that it's being marketed as the new thing.
For instance, look at his solution to FizzBuzz. Would you use a similar solution in ruby? He uses an infinite list, so if you naively translated it, you'd run out of memory. Instead, you'd have to explicitly use a generator in order to achieve a similar solution.
Of course, you can try always returning a generator in ruby, but that would be incredibly awkward because the built-in operators compute the entire result (like the + operator on lists). So, in practice, people intuitively avoid creating large intermediate results because it's wasteful, even in cases where that would simplify the code and make it more modular.
But in haskell, go ahead and use the large intermediate result, because it won't actually compute it before returning. It will just return a generator for the large intermediate result, and compute only the parts of that large result that are needed.
List.map data ~f:(fun elem -> ...)
|! List.find ~f:( ... )
|! Option.map ~f:( ... )
(This is OCaml, not Haskell, but the syntax is similar.) The definition of the '|!' operator is quite simple: let (|!) x f = f x (|>) :: a -> (a->b) -> b
(|>) x f = f x
infixl 0 |>
There infixl 0 means infix operator with left associativity and 0 precedence.Then you can use all sorts of expressions inbetween:
(5 + 3 |> show) ++ " times" |> putStrLn
Also, tying this back to one of the article's ideas, this piping-like syntax for doing things really manages to take away the emphasis from the function and put it back on the data. It isn't all about functions after all!Eg:
(reduce + (take 10 (filter even? (map #(* % %) (range)))))
Can be expressed as:
(->> (range)
(map #(* % %))
(filter even?)
(take 10)
(reduce +))http://book.realworldhaskell.org/read/code-case-study-parsin...
(also you can read about the F# (|>) forward pipe, and there'll be operator precedence/associativity and thunk forcing issues)