Posts tagged with functional programming

Classes, complexity, and functional programming

In this article Kent C. Dodds clearly explains what the downsides are of using Class in JavaScript.

Classes (and prototypes) have their place in JavaScript. But they’re an optimization. They don’t make your code simpler, they make it more complex. It’s better to narrow your focus on things that are not only simple to learn but simple to understand: functions and objects.

https://medium.com/@kentcdodds/classes-complexity-and-functional-programming-a8dd86903747

Read more

Join 9,500+ smart developers

Every month I share what I learn from running Spatie, building Oh Dear, and maintaining 300+ open source packages. Practical takes on Laravel, PHP, and AI that you can actually use.

No spam. Unsubscribe anytime. You can also follow me on X.

Understanding Laravel’s HighOrder Collections

One of my favourite features that was introduced in Laravel 5.4 are the higher order collection functions. It allows you to rewrite

collect($models)->filter(function(Model $model) {
   $model->passesFilter();
});

to:

collect($models)->filter->passesFilter();

This works with the filter method an a bunch of other collection methods.

In a new post on his blog Nicola Malizia explains how these methods work under the hood.

A new version of Laravel is available from 24 January 2017 and, as usual, it comes with a lot of new features. Among them, there is one that takes advantage of the dynamic nature of PHP. Some out of there will contempt this, but I find it awesome!

https://unnikked.ga/understanding-laravels-highorder-collections-ee4f65a3029e

Read more

Closure Binding as an alternative to “use” variables

On his blog Mark Baker shares some thoughts on how to use closure binding to avoid having import variables with the use keyword.

You'll learn how to rewrite

$filteredArrayData = array_filter(
    $arrayData,
    function($value) use ($minimumPrice, $maximumPrice) {
        return $value->price >= $minimumPrice &amp;&amp; $value->price < $maximumPrice;
    }
);

to

$filteredArrayData = array_filter(
    $bookData,
    $priceFilter->inRange(5.00, 15.00)
);

https://markbakeruk.net/2017/03/12/closure-binding-as-an-alternative-to-use-variables/

Read more

10 Lodash Features You Can Replace with ES6

In the JavaScript world Lodash is a pretty popular and awesome package with lots of handy array, collection and object methods. In this article Dan Prince explains that some of those methods do have a nice ES6 equivalent.

Lodash is the most depended on npm package right now, but if you’re using ES6, you might not actually need it. In this article, we’re going to look at using native collection methods with arrow functions and other new ES6 features to help us cut corners around many popular use cases.

https://www.sitepoint.com/lodash-features-replace-es6/

Read more

Glossary of Modern JavaScript Concepts

Don't know what the difference between stateful and stateless is, or what higher order functions are? On the auth0.com site Sebastián Peyrott explains these terms and other modern JavaScript concepts.

Modern JavaScript has experienced massive proliferation over recent years and shows no signs of slowing. Numerous concepts appearing in JS blogs and documentation are still unfamiliar to many front-end developers. In this post series, we'll learn intermediate and advanced concepts in the current front-end programming landscape and explore how they apply to modern JavaScript.

https://auth0.com/blog/glossary-of-modern-javascript-concepts/

Read more

An introduction to functional programming

On Egghead.io there's a free course available on functional programming. Your teacher is Professor Frisby, who is in fact a hedgehog. Yup, you've read that right. The tempo of the course is quite fast, so you might have to, like me, pause or rewatch the videos to get the most out of it.

This course teaches the ubiquitous abstractions for modeling pure functional programs. Functional languages have adopted these algebraic constructs across the board as a way to compose applications in a principled way.

We can do the same in JavaScript. While the subject matter will move beyond the functional programming basics, no previous knowledge of functional programming is required. You'll start composing functionality before you know it.

https://egghead.io/courses/professor-frisby-introduces-composable-functional-javascript

Read more

Is your JavaScript function actually pure

What does “pure function” mean in the context of JavaScript? In programming in general, purity is also known as “referential transparency”, a fancy way of saying “replacing an expression or function call with its result will never change the behavior of the program” or a way of saying “every time you pass the same inputs, you always get the same outputs”.

That sounds intuitive, and a function like x => x * 10 looks pure because every single time you pass it the number 3 as argument you will get 30 as output. So how can we tell that one function is pure and the other isn’t? Is it enough that we just read the code?

Spoiler: reading the code isn't enough.

http://staltz.com/is-your-javascript-function-actually-pure.html

Read more

Code Golf

When starting out programming many developers are quite happy when their code just works. More seasoned programmers know that making working code is just a first step. Not improving your initial code will lead to professional suicide (not my phrasing, I'm sure I've read this in a book at some point).

In an article on his blog, Colin DeCarlo demonstrates how an initial solution can be vastly improved in just a few iterations.

From time to time a friend and I play a programming game that I consider to be a version of Code Golf. Typically, the goal of Code Golf is to solve some challenge using as little bytes as possible. In the version of the game we play however, the limitation is the use of certain language features. Specifically, we try to use as little variables, conditionals and explicit loops as possible.

...

My method to accomplishing these challenges is to first write the algorithm in the simplest, most straight forward manner and then chip away at that solution until I’ve satisfied the challenge conditions.

The focus in the article is on removing conditionals, and limiting the use of variables. Keep in mind that, in most cases, this shouldn't be your main goal. Maximizing the readabilty is what your should pursue. Don't try to be too clever or terse. In some cases limiting conditionals and variables goes hand in hand with improving readability, in other cases not. It all depends on context.

Read more

Functional programming design patterns

In object-oriented development, we are all familiar with design patterns such as the Strategy pattern and Decorator pattern, and design principles such as SOLID.

The functional programming community has design patterns and principles as well.

This talk will provide an overview of some of these, and present some demonstrations of FP design in practice.

Watch it on Vimeo.

Read more

Recursion and Generators

Christopher Pitt experimented a bit with generators and wrote down the thought process on his blog.

Generators are awesome. If they’re new to you then take some time to read where they come from and what they do. If you’ve come from a particular programming language background, they may be difficult for you to understand.

They were, and continue to be, tricky for me to grasp. So I’ve spent loads of time trying to understand them, and what they can do for my code.

https://medium.com/@assertchris/recursion-and-generators-d56f513ea6ab

Read more

Higher order functions in JavaScript

Functions that operate on other functions, either by taking them as arguments or by returning them, are called higher-order functions. If you have already accepted the fact that functions are regular values, there is nothing particularly remarkable about the fact that such functions exist. The term comes from mathematics, where the distinction between functions and other values is taken more seriously.
http://eloquentjavascript.net/05_higher_order.html

Read the article for some clear examples to help you understand the concept.

Read more

Higher order programming

This weekend at the PHPBenelux 2015 conference I went to a session about higher order programming by Mathias Verraes. Higher-order programming is a style of programming that uses functions as values.

During the session Mathias demonstrated his Lamdalicious library. This library brings the principles of LISP to PHP. The talk was very fast paced and everything was live coded. PHP was misused to the fullest: global variables, error suppression, ... and there was lots of recursion going on. Basically he was constructing another language in PHP. During the talk there were lots of ooohhss and aaahhhss in the room, so I suspect I was not the only one enjoying it.

If you are intrigued by this, be sure to read his blog post on the subject. The blog post is essentially the written down version of the talk.

You'll never use any of this code in production, but that's not the goal of the library. Like when doing code katas, the train of thought is much more important than the result.

Here's another wonderful blog post.

Read more

Functional programming in PHP

Almost a year ago Igor Wiedler wrote three articles on his blog about the state of functional programming in PHP.

The first article explores iteration. You'll learn to turn this


$admins = [];
foreach ($users as $user) {
    if (is_admin($user)) {
        $admins[] = $user;
    }
}

into this


use function iter\filter;
$admins = filter('project\user\is_admin', $users);

In the second one he explains a very nice way to traverse an associative array. How you currently do it:


$baz = (isset($data['foo']['bar']['baz'])) ? $data['foo']['bar']['baz'] : null;

How you'll do it in the future:


use function igorw\get_in;
$baz = get_in($data, ['foo', 'bar', 'baz']);

The final article shows you a nice syntax to handle objects that return null-values.

All the articles mention libraries that you can use in your code today.

Read more