Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I write an app that doesn't change state (in functional language)?

I want to learn functional programming one day but I don't understand how I could use it for anything other than simple math.

For example: A simple web browser add bookmark function needs to cause some sort of mutation so that next time the user clicks bookmarks the new bookmark is there in the list.

like image 492
Tim Matthews Avatar asked Jan 25 '09 08:01

Tim Matthews


People also ask

How do you maintain state in functional programming?

In pure functional programming, state is manipulated by functions that take some state and return the next state. Sequencing through states is then achieved by passing the state through a sequence of pure functions. Even global mutable state can be modeled this way.

Can you use for loop in functional programming?

Bookmark this question. Show activity on this post. We dont use for loop in functional programming, instead, we use higher order functions like map, filter, reduce etc. These are fine for iterating through an array.

Can you do functional programming in any language?

A short answer is yes, you can do functional programming in any language. The long answer is you probably don't want to. One reason is that relying on discipline might work if you're writing a small program or you're writing a program by yourself or on a very small team, you can handle the discipline of it.

Why is Python not a functional language?

Python doesn't have built in support for efficient manipulation of immutable structures as far as I know. That's one large knock against it, as immutability can be considered a strong aspect of FP. It also doesn't support tail-call optimization, which can be a problem when dealing with recursive solutions.


1 Answers

A useful application as a whole will often have to change state of several things, but that doesn't mean that all or your functions need to change state to be useful.

Monads in functional programming are to express input/output (I/O) operations and changes in state without using language features that introduce side effects.

I think you are thinking only in terms of object oriented. Just because a function always gives the same output given the same input, doesn't mean that it can't take in different types of input (possibly infinite possibilities of input) and produce different types of output.

With functional programming you are dealing with immutable objects instead of mutable ones. If you get input of an object, you can create a new modified object and return that.

Take a look at this article about MapReduce by Joel on software. It contains a pretty good example about why a function that does not change state can be completely useful.

like image 87
Brian R. Bondy Avatar answered Sep 22 '22 19:09

Brian R. Bondy