dbrattli / Expression

Pragmatic functional programming for Python inspired by F#
https://expression.readthedocs.io
MIT License
421 stars 30 forks source link

How are the collections implemented? #92

Closed ShalokShalom closed 1 year ago

ShalokShalom commented 1 year ago

I see that you provide different collections with immutability in mind.

Are they also implemented as immutable data structures?

If not, I recommend adding that info to the README section, that cares about the differences to FSharp.

In that case, I do suggest this as feature. :)

If it does, I recommend adding that info to the README as well.

dbrattli commented 1 year ago

@ShalokShalom the collections are implemented as immutable data-structures, but in Python nothing is really immutable except str, tuple, so for example the Block is an immutable list built on a tuple, and using the Block with the API provided will keep it immutable. But the class containing the tuple is not immutable, so you could always replace the tuple. We could try to make that harder to do, but it's not really the goals of this library to work around such issues with Python. But for classes like Block we could improve things and make the contained value e.g prefixed with underscore or double underscore.

ShalokShalom commented 1 year ago

Oh, I mean do they copy or reference? I mean, are they efficient, as immutable data structures in Clojure or FSharp? Or do they really copy stuff around, even though nothing is changed?

dbrattli commented 1 year ago

At least the Map implementation is the exact same code as F#. Block uses tuples which should be very efficient (since Python knows they are immutable and backed by c-code). I'm considering changing the Fable List impl. to use tuples when targeting Python. But it's hard to optimize lists. They just get better at one thing, and worse at another 😄

ShalokShalom commented 1 year ago

Exact same code? You mean you transpiled your/a F# map implementation to Python?

dbrattli commented 1 year ago

Yes, I could have done that now using Fable, but at the time I did it manually line by line. You can see that the Fable code (to the right) is not that different from Expression (on the left), but Fable still has a few more typing issues.

Screenshot 2022-09-21 at 11 03 34
ShalokShalom commented 1 year ago

Oh wow, thats impressive on both sides 😄