<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Oleg Stotsky on Medium]]></title>
        <description><![CDATA[Stories by Oleg Stotsky on Medium]]></description>
        <link>https://medium.com/@olegstotsky?source=rss-328c8fe2e5d8------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*MtsdWD8juDlC5LAPAA52Iw.jpeg</url>
            <title>Stories by Oleg Stotsky on Medium</title>
            <link>https://medium.com/@olegstotsky?source=rss-328c8fe2e5d8------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Wed, 02 Dec 2026 18:08:18 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@olegstotsky/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Using monads with go 1.18 generics (Part 1 — Maybe)]]></title>
            <link>https://levelup.gitconnected.com/using-monads-with-go-1-18-generics-part-1-maybe-bb42d3e09968?source=rss-328c8fe2e5d8------2</link>
            <guid isPermaLink="false">https://medium.com/p/bb42d3e09968</guid>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[golang-tutorial]]></category>
            <category><![CDATA[functional-programming]]></category>
            <category><![CDATA[golang]]></category>
            <category><![CDATA[haskell]]></category>
            <dc:creator><![CDATA[Oleg Stotsky]]></dc:creator>
            <pubDate>Sun, 08 May 2022 12:51:35 GMT</pubDate>
            <atom:updated>2022-05-23T01:38:09.388Z</atom:updated>
            <content:encoded><![CDATA[<h3>Using monads with go 1.18 generics (Part 1 — Maybe)</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/339/1*hcH45UTXMb0UmUiQ4EqoTA.png" /></figure><p>Go 1.18 introduced long awaited generics to go programming language. With this update, a lot of new possibilities for type safe programming have been added.</p><p>One of these possibilities is using a well known pattern that came from functional programming called monads. Monads are a way to wrap your computations in containers that glue your computations together, producing some effects along the way. For example, in Haskell you can’t perform any side effects directly — you need to wrap them in IO monad, which we will talk about later.</p><p>Let’s start with the simplest monad — Maybe. Maybe is a container that either has a value or nothing. It has some methods that allow us to combine them together, filter, and get values out of them.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/1f07964b98f8cc9e233dee30a780d0e3/href">https://medium.com/media/1f07964b98f8cc9e233dee30a780d0e3/href</a></iframe><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d02eca5af673f65b72e76605147743c4/href">https://medium.com/media/d02eca5af673f65b72e76605147743c4/href</a></iframe><p>There are 2 implementations of this interface — one for the case when we have value, and one for the case when we have nothing.</p><p>The simplest way to chain Maybe computations is by using Map and FlatMap:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/3378f0023ac883811ca02b3468c7610b/href">https://medium.com/media/3378f0023ac883811ca02b3468c7610b/href</a></iframe><p>Map takes any function that takes value and returns value and applies this function to our Maybe value m. If m has value, it runs the function on it, if it doesn’t have value, it does nothing. This way, if we have a long sequence of computations in which the first one might fail and return nothing, we don’t have to write if checks on every stop along the way.</p><p>FlatMap works the same way but for a function that also returns Maybe.</p><p>There are also some utility methods like IsPresent which returns true on Just and false on Nothing.</p><p>Now let’s look at some practical example on how we can reduce some code clutter using maybe monad.</p><p>Let’s say we have the following sequence of divisions:</p><p>x := a / b</p><p>y := c/x</p><p>z := d/ y</p><p>b and d can be zeroes and x and y can also be zeroes.</p><p>Here is how we could implement it using if statements:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/79bf2207b357124fe7f3ab78cc45a6e6/href">https://medium.com/media/79bf2207b357124fe7f3ab78cc45a6e6/href</a></iframe><p>Using Maybe monad:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/4f10fb64d4079a9ec79863fd78ea9da1/href">https://medium.com/media/4f10fb64d4079a9ec79863fd78ea9da1/href</a></iframe><p>Complete code for Maybe monad:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/7f685693ad54a537016029230b73c619/href">https://medium.com/media/7f685693ad54a537016029230b73c619/href</a></iframe><p>You can find these code as well as code for other monads in<a href="https://github.com/OlegStotsky/go-monads"> go-monads github repo</a>. In the next post in this series we will look at IO monad. Stay tuned!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=bb42d3e09968" width="1" height="1" alt=""><hr><p><a href="https://levelup.gitconnected.com/using-monads-with-go-1-18-generics-part-1-maybe-bb42d3e09968">Using monads with go 1.18 generics (Part 1 — Maybe)</a> was originally published in <a href="https://levelup.gitconnected.com/">Level Up Coding</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Persistent Data Structures for Gophers: Persistent Stack]]></title>
            <link>https://levelup.gitconnected.com/persistent-data-structures-for-gophers-persistent-stack-70aa012d3bfa?source=rss-328c8fe2e5d8------2</link>
            <guid isPermaLink="false">https://medium.com/p/70aa012d3bfa</guid>
            <category><![CDATA[golang]]></category>
            <category><![CDATA[computer-science]]></category>
            <category><![CDATA[go]]></category>
            <category><![CDATA[concurrency]]></category>
            <category><![CDATA[benchmark]]></category>
            <dc:creator><![CDATA[Oleg Stotsky]]></dc:creator>
            <pubDate>Sat, 21 Nov 2020 15:06:39 GMT</pubDate>
            <atom:updated>2020-11-22T12:28:50.597Z</atom:updated>
            <content:encoded><![CDATA[<p>In this series of blog posts I would like to explore the world of immutable persistent data structures, their pros and cons compared to mutable data structures, cover in which scenarios we would want to use them and provide some theoretical background.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/200/0*Oe1TwZiF1PHYSHlm.jpg" /></figure><p>First of all, let’s define what immutable data structure is. According to wikipedia:</p><blockquote>In computing, a persistent data structure is a data structure that always preserves the previous version of itself when it is modified. Such data structures are effectively immutable, as their operations do not (visibly) update the structure in-place, but instead always yield a new updated structure.</blockquote><p>We can immediately see several benefits compared to mutable counterparts:</p><ol><li>Since we don’t have mutable state, we don’t have to worry that the methods we call will accidentally mutate our variables</li><li>We don’t have to use synchronization such as locks, which in theory should increase performance when the lock contention is high</li><li>We have all versions of our structure, which can come very handy if we want to do something like undo-redo.</li></ol><p>Let’s see what this means in practice by building immutable stack. Stack is an abstract data type that supports the following operations:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/96706eb9078c626bceed69e144757204/href">https://medium.com/media/96706eb9078c626bceed69e144757204/href</a></iframe><p>First, lets create a mutable stack to see how implementation would look like and to provide a reference point:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/7e5a503e1072806ca92ca229f8cf4a34/href">https://medium.com/media/7e5a503e1072806ca92ca229f8cf4a34/href</a></iframe><p>We use mutable slice to store the elements and we have to use lock in order to avoid race conditions. Asymptotic complexity wise, all operations cost O(1).</p><p>Now let’s see what implementation of persistent stack looks like:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/091667c1b0e591ae926bd7fd1a66767d/href">https://medium.com/media/091667c1b0e591ae926bd7fd1a66767d/href</a></iframe><p>Everything is straightforward: we use a separate type to represent empty stack to reduce code clutter. We also use a static instance of empty stack to reduce memory overhead, since it has no state and therefore can be shared. Push creates a new version of stack and returns it and pop just returns a tail which provides us with complete history of changes that we discussed. Note that we never mutate a state and therefore we never have to use locks.</p><p>Persistent stack is a very nice data structure since all operations have the exact same asymptotic complexity as in the mutable implementation, but provide great benefits that mutable implementation doesn’t. When we will explore other persistent data structures we will learn that this isn’t always the case.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/300/0*4FaWtICEv3vctnif.jpg" /></figure><p>Now let’s do some benchmarks to see how immutable implementation scores against the mutable one. I’ve designed a small use case in which stack comes in very handy: suppose we are building a drawing application with vectorized graphics. All drawn points are represented as vectors, which themselves are represented as pairs of points.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/117dda26500f3f21a6b50d81fdb96272/href">https://medium.com/media/117dda26500f3f21a6b50d81fdb96272/href</a></iframe><p>And two data structures that will hold history of user’s edits: mutable stack and immutable stack</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/126e076aec1dc1adddeddc856c5f9574/href">https://medium.com/media/126e076aec1dc1adddeddc856c5f9574/href</a></iframe><p>Not that in immutable version we have to store the stack in unsafe.Pointer, since we need to hold current version of the stack, and in order to do that we must me able to update the pointer to current version atomically, which can be done using atomic.CompareAndSwapPointer.</p><p>Let’s start with benchmarks that compare push performance:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e7f97d0517ea359ba9cc8e1f052d0725/href">https://medium.com/media/e7f97d0517ea359ba9cc8e1f052d0725/href</a></iframe><p>We get the following results:</p><pre>BenchmarkMutableStackPush/push_with_1_g-6  9494250 115 ns/op<br>BenchmarkMutableStackPush/push_with_5_g-6  9068743 131 ns/op<br>BenchmarkMutableStackPush/push_with_100_g-6 5516866 221 ns/op<br>BenchmarkMutableStackPush/push_with_1000_g-6 5231342 227 ns/op<br>BenchmarkMutableStackPush/push_with_5000_g-6 5698480 243 ns/op</pre><p>For a quick reminder on how RunParallel works: it distributes b.N iterations among number of goroutines defined by SetParallelism. So, in ideal scenario, if we increase a number of goroutines to N, where N is ≤ number of CPUs, we should see a performance increase up to N times. Which is totally not the case, however, as we can see in the benchmarks: going from having 1 goroutine to 5 doesn’t increase performance, but actually runs a bit slower! To understand why, let’s run benchmark with profiler, and see what takes up most of the time of our benchmark.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/759/1*4-a5jUaRu2nc-2abGB4bEQ.png" /><figcaption>profiling results</figcaption></figure><p>As we can see, 74% percent of the time is spent in locking/unlocking mutex, which means we have only 26% of the room for parallelism.</p><p>Let’s see how immutable stack compares to mutable stack in push benchmark. Push benchmark code:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a31c8d62302e8feea8b40f3104135b4a/href">https://medium.com/media/a31c8d62302e8feea8b40f3104135b4a/href</a></iframe><p>As you see, we have to spin a loop until CompareAndSwapPointer returns true, which happens only when the current oldVal equals the value in h.history. We need to do this since between the time we create a new version of stack by calling Push and the time we call CompareAndSwapPointer, other goroutine could have already updated the value h.history, so our update becomes invalid.</p><p>Results:</p><pre>BenchmarkImmutableStackPush/push_with_1_g-6 3585588 433 ns/op<br>BenchmarkImmutableStackPush/push_with_5_g-6 4179456 339 ns/op<br>BenchmarkImmutableStackPush/push_with_100_g-6 2486130 493 ns/op<br>BenchmarkImmutableStackPush/push_with_1000_g-6 3969709 394 ns/op<br>BenchmarkImmutableStackPush/push_with_5000_g-6 6096267 341 ns/op</pre><p>As you can see, we get outperformed by mutable stack. Why is that? Let’s run the code with profiler and see what takes most of the time:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a31c8d62302e8feea8b40f3104135b4a/href">https://medium.com/media/a31c8d62302e8feea8b40f3104135b4a/href</a></iframe><p>As we can see, most of the time is spent allocating new objects and collecting garbage.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/954/1*bWbC88ESeNQ7Wk_PB85aEA.png" /></figure><p>One way we could try to fix this is by preallocating a pool of objects using sync.Pool and returning instances from it instead of allocating new ones. Let’s do that.</p><p>Code:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d46e532013dcec447df30f52d4267730/href">https://medium.com/media/d46e532013dcec447df30f52d4267730/href</a></iframe><p>Benchmark results:</p><pre>ImmutableStackPushWithPool/push_with_1_g-6 5884106 229 ns/op<br>ImmutableStackPushWithPool/push_with_5_g-6 5945172 208 ns/op<br>ImmutableStackPushWithPool/push_with_100_g-6 6525007 273 ns/op<br>ImmutableStackPushWithPool/push_with_1000_g-6 6722889 203 ns/op<br>ImmutableStackPushWithPool/push_with_5000_g-6  7014976 203 ns/op</pre><p>Indeed, using sync.Pool made performance on par with the mutable version, since we relieved the weakest point of the implementation -pressure on garbage collector.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d6be275f60f292c752e78580bbef183a/href">https://medium.com/media/d6be275f60f292c752e78580bbef183a/href</a></iframe><p>Now let’s look at how performance changes when Push is mixed with Top. Let’s write a benchmark that calls Top on even iterations and Push on odd ones. Code for mutable stack:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/de9dcf8babc100fbffe1bcde46d585f0/href">https://medium.com/media/de9dcf8babc100fbffe1bcde46d585f0/href</a></iframe><p>Results:</p><pre>BenchmarkMutableStackPushAndTop/push_with_1_g-6 10864327 233.0 ns/op<br>BenchmarkMutableStackPushAndTop/push_with_5_g-6 11345487 212 ns/op<br>BenchmarkMutableStackPushAndTop/push_with_100_g-6 5179686 227 ns/op<br>BenchmarkMutableStackPushAndTop/push_with_1000_g-6 5018956 202 ns/op<br>BenchmarkMutableStackPushAndTop/push_with_5000_g-6 7064036 204 ns/op</pre><p>Code for immutable stack:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/62fe73b5dd374f58e206b1403f13d095/href">https://medium.com/media/62fe73b5dd374f58e206b1403f13d095/href</a></iframe><pre>ImmutableStackPushAndTop/push_with_1_g-6  11457074 261 ns/op<br>ImmutableStackPushAndTop/push_with_5_g-6 12009836 301 ns/op<br>ImmutableStackPushAndTop/push_with_100_g-6 11332501 262 ns/op<br>ImmutableStackPushAndTop/push_with_1000_g-6 10732173 264 ns/op<br>ImmutableStackPushAndTop/push_with_5000_g-6 11492300 256 ns/op</pre><p>As we can see, the results are on par with mutable stack this time. This is due to the fact that we don’t have to do as much allocations, therefore we spend less time in GC, and, unlike the mutable stack, we don’t spend time in locks when we call Top. But what if we run the immutable version with the pool?</p><pre>ImmutablePooledStackPushAndTop/push_with_1_g-6 11825787 127 ns/op<br>ImmutablePooledStackPushAndTop/push_with_5_g-6 11818896 119 ns/op<br>ImmutablePooledStackPushAndTop/push_with_100_g-6 12145059 129 ns/op<br>ImmutablePooledStackPushAndTop/push_with_1000_g-6 11344802 120 ns/op<br>ImmutablePooledStackPushAndTop/push_with_5000_g-6 11398592 127 ns/op</pre><p>We are able to beat the mutable stack by a factor of two! This is because pooled immutable stack has a best of both worlds: no locks due to being immutable, and smaller GC overhead due to using sync.Pool.</p><p>Benchmark results as a table:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/27f59b3bc2298d186103d959b9263739/href">https://medium.com/media/27f59b3bc2298d186103d959b9263739/href</a></iframe><p>As we can see, the results are not so obvious. However, depending on the concrete proportion of Push/Top calls, immutable stack could be a nice tool in our toolbox when we need to get that last percents of performance. In the next posts in this series I will look into more immutable data structures, explain their use cases and explore their performance. All of the code can be found on github in <a href="https://github.com/OlegStotsky/go-persistent">this repository</a>. Feel free to contribute.</p><p>Thanks for reading and stay tuned for new posts!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=70aa012d3bfa" width="1" height="1" alt=""><hr><p><a href="https://levelup.gitconnected.com/persistent-data-structures-for-gophers-persistent-stack-70aa012d3bfa">Persistent Data Structures for Gophers: Persistent Stack</a> was originally published in <a href="https://levelup.gitconnected.com/">Level Up Coding</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>