Is assignment with "let" not against the idea of functional programming in Clojure

321 views Asked by At

Assignment should avoided in functional programming, but in clojure we often use let.

Is let just a way of being practical or is assignment not the same as using let? Should we not avoid assignment in functional programming?

2

There are 2 answers

1
Chris On BEST ANSWER

Mutable state is generally against the core concepts of functional programming.

However, let merely binds a name to a value. If that value is immutable, there's no reason for it to be inconsistent with functional programming ideals.

0
Gwang-Jin Kim On

One cannot say that assignment in general is against the idea of functional programming (FP).

A def expression is an assignment as well as a let expression. Giving names to things and procedures/functions is a mean of abstraction - and programming means to a big part applying abstraction on recurring problems.

Imperative style misuses assignments for mutation and thus creating/maintaining/mapping of (global) states. Mutation is not possible without assignment. So FP aims against such kind of mutations not assignments per se.

Actually FP is not even aiming against mutation per se. Even in functional languages mutation is in some situations required for performance reasons.

There is harmless mutation - mutation of variables which are anyway never ever again referred to for the rest of the program - e.g. because they appear only within a certain scope (e.g. within the scope of a let expression or a function definition). I tend to call them 'benign' mutations. And there is harmful mutation - mutation of variables to which later is referred to - mutation of variables which go on living outside the scope they were created in - thus constituting some kind of an unlimited state. I call them 'malign' mutations.

Actually it is also wrong to say FP avoids state alltogether.

Closures are actually constituting states in FP. Through closures functions can refer to hidden variables which keep a "memory"/state between different function calls. But they are applied in a very controlled manner.

Probably this is why defining FP is so difficult. Very quickly one has oversimplified something thereby causing more confusion than clarifying things.