My question is about mutability of 'state machine' object in FRP. I'm evaluating Bacon.js's Observable.withStateMachine.
My domain is trading robots. I've got a source event stream of 'Orders' which actually are tuples (buy or sell,price,volume)
I want to use something like the following pseudocode ```
orders.withStateMachine(new Book(), function(book,order) { // is 'book' mutable ?!!
var bookModifiedEvents = book.merge(order);
return [book, modifications];
})
Book.prototype.merge = function(order) {
// either append order into the Book, or generate Trade when order gets filled.
// generate corresponding bookModifiedEvents and tradeEvents.
return bookModifiedEvents.merge(tradeEvents);
}
```
This code shoud aggregate exchange orders into order book (which is a pair of priorityqueues for bids and asks orders sorted by price) and publish 'bookModified' and 'tradeOccured' event streams.
What I don't quite understand: Can I directly modify initial state object that was passed to my callback I give to .withStateMachine method?
Since FRP is all about immutability, I think I shouldn't. In such case I should create a lot of orderbook objects, which are very heavy (thousands of orders inside).
So I began to look to immutable collections, but, first, there is no immutable priority queue (if it makes sense), and, second, I'm afraid the performance would be poor for such collections.
So, finalizing, my question has 2 parts:
1) In case of HEAVY STATE, is it LEGAL to modify state in .withStateMachine?? Will it have some very-very bad side effects in bacon.js internals?
2) And if it is NOT allowed, what is recommended? Immutable collections using tries? Or some huge refactoring so I will not need orderbooks as phenomena in my code at all?
Thanks.
The whole idea of reactive programming doesn't work, if you mutate data or cause side-effects in something which is expected to be referentially transparent.
So 1) modifying the state isn't illegal, but you can run into undefined behaviour scenarios. So you are on your own.
2) And as mutation isn't recommended, what is an alternative: Try immutable.js
as you mentioned it, make priority queue build on top of List or whatever is more suitable. Don't prejudge the performance. Immutable collections use sharing, so when you copy a collection, you don't need to copy the elements as they could be shared (they are assumed to be immutable too - why to copy stuff we aren't changing).