HNHacker News
TopNewBestAskShowJobs

louthy

6,853 karma · joined March 9, 2012

London based founder of meddbase.com (now sold)

Author: github.com/louthy/language-ext

* blog: paullouth.com

* bsky: @paullouth.bsky.social

* mast: 4four.org/@louthy

submissionscomments
louthy··on I dumped Windows 11 for Linux, and you should too
Don't buy one then.
louthy··on I dumped Windows 11 for Linux, and you should too
Nothing is quite as slick as Apple, but companies are popping up doing pretty sleek Linux-first laptops, I have a Starlabs notebook [1] and am waiting for their new Starfighter [2]...

[1] https://starlabs.systems/pages/starbook-horizon

[2] https://starlabs.systems/pages/starfighter

louthy··on Mathematics for Computer Science (2018) [pdf]
TAOCP
louthy··on I program without syntax highlighting
> Most syntax highlighting adds too many color variations.

Different strokes, for different folks. I personally use Monokai where each token type has and ‘extreme’ colour (like full red, full green, full yellow, etc.) — I absolutely love it and, for me, makes code much easier to parse

louthy··on Monads in C# (Part 2): Result
It’s not about danger it’s about being declarative. That’s kinda the point of using these ‘result’ types: you’re fully declaring the codomain of the function — barring exceptions — and so if your codomain is augmented with Exception then it’s pretty hard to know whether all exceptions will be returned in value form, or just exceptional exceptions! It’s fails the declarative test.
louthy··on Monads in C# (Part 2): Result
I think you mean Left. And Left in Fin is Error, which has two subtypes: Expected and Exceptional, along with bespoke matching primitives for exceptional and non-exceptional errors (for the reasons I outlined)

I understood what they meant, Exception is still a poor type for declarative error handling, because it’s unclear whether an event is truly exceptional.

louthy··on Monads in C# (Part 2): Result
If you ask yourself what the meaning of the word 'exception' is and then consider how many failures are exceptional, then one quickly realises that exceptions are the worst thing you could use to represent expected failure conditions.

The only time we should throw (or even pass around) exceptions is if there isn't a slot in the co-domain to inject a value in to.

louthy··on Monads in C# (Part 2): Result
On your definition of FP you're right. But pure functional programming has the following over regular imperative coding:

* Fewer bugs: Pure functions, which have no side effects and depend only on their input parameters, are easier to reason about and test, leading to fewer bugs in the code-base.

* Easier optimisation: Since pure functions do not have any side effects, they can be more easily optimised by the compiler or runtime system. This can lead to improved performance.

* Faster feature addition: The lack of side effects and mutable state in pure functional programming makes it easier to add new features without introducing unintended consequences. This can lead to faster development cycles.

* Improved code clarity: Pure functions are self-contained and independent, making the code more modular and easier to understand. This can improve code maintainability.

* Parallelisation: Pure functions can be easily parallelised, as they do not depend on shared mutable state, which can lead to improved scalability.

* Composition: This is the big one. Only pure functional programming has truly effective composition. Composition with impure components sums the impurities into a sea of undeclared complexity that is hard for the human brain to reason about. Whereas composing pure functions leads to new pure functions – it's pure all the way down, it's turtles all the way down. I find it so much easier to write code when I don't have to worry about what's going on inside every function I use.

That's obviously way beyond just having a declarative return type. And in languages like C# you have to be extremely self-disciplined to 'do the right thing'. But what I've found (after being a procedural dev for ~15 years, then a OO dev for ~15 years, and now an FP dev for about 12 years) is that pure functional programming is just easier on my brain. It makes sense in the way that a mathematical proof makes sense.

YMMV of course, but for me it was a revelation.

louthy··on Monads in C# (Part 2): Result
Aww, thanks Mike! And thank you for the contributions and suggestions too :)

> At this point basically everyone has been exposed to the concept of `Option/Result/Either/etc. and discussions typically end up revolving around the aesthetics of exception throwing vs. method chaining vs. if statements etc. without any concept of the bigger picture.

I think this is a really important point. 12 years ago I created a project called 'csharp-monad' [1], it was the forerunner to language-ext [2], which I still keep on github for posterity. It has the following monadic types:

    Either<L, R>
    IO<T>
    Option<T>
    Parser<T>
    Reader<E,T>
    RWS<R,W,S,T>
    State<S,T>
    Try<T>
    Writer<W,T>
One thing I realised after developing these monadic types was that they're not much use on their own. If your List<T> type's Find method doesn't return Option<T>, then you haven't gained anything.

I see others on here are taking a similar journey to the one I took over a decade ago. There's an obsession over creating Result types (Either<L, R> and Fin<A> in language-ext, btw) and the other basic monads, but there's no thought as to what comes next. Everyone of them will realise that their result-type is useless if nothing returns it.

If you're serious about creating declarative code, then you need an ecosystem that is declarative. And that's why I decided that a project called "csharp-monad" was too limiting, so I started again (language-ext) and I started writing immutable collections, concurrency primitives, parsers, and effect systems (amongst others). Where everything works with everything else. A fully integrated functional ecosytem.

The idea is to make something that initially augments the BCL and then replaces/wraps it out of existence. I want to build a complete C# functional framework ecosystem (which admittedly is quite an undertaking for one person).

I'm sometimes a little wary about going all in on the evangelism here. C# devs in general tend to 'stick to what they know' and don't always like the new, especially when it's not idiomatic - you can see it in a number of the sub-threads here. But I made a decision early on to fuck the norms and focus on making something good on its own terms.

And for those that wonder "Why C#?" or "Why not F#?", well C# has one of the best compilers and tooling ecosystems out there, it's got an amazing set of functional language features, it will have ADTs in the next version, and it has a strong library ecosystem. It also has the same kind of borrow checker low level capability as Rust [3]. So as an all-rounder language it's quite hard to beat: from 'to the metal bit-wrangling', right the way up to monad comprehensions. It should be taken more seriously as a functional language, but just generally as a language that can survive the turmoil of a long-lived project (where mostly you want easy to maintain code for the long-term, but occasionally you might need to go in and optimise the hell out of something).

My approach will piss some people off, but my aim is for it to be like the Cats or Scalaz community within the larger Scala community.

It's certainly a labour of love right now. But, over a decade later I'm still enjoying it, so it can't be all bad.

(PS Mike, I have new highly optimised Foldable functionality coming that is faster than a regular C# for-loop over an array. Watch this space!)

[1] https://github.com/louthy/csharp-monad

[2] https://github.com/louthy/language-ext

[3] https://em-tg.github.io/csborrow/

louthy··on Monads in C# (Part 2): Result
Fair enough :)

By the way, I happen to agree on the general point, in my blog teaching Monads in C# [1], I wrote this:

"I often see other language ecosystems trying to bring monads into their domain. But, without first-class support for monads (like do notation in Haskell or LINQ in C#), they are (in my humble opinion) too hard to use. LINQ is the killer feature that allows C# to be one of very few languages that can facilitate genuine pure functional programming."

So, yeah, regular fluent method chaining isn't really enough to make monads useful.

[1] https://paullouth.com/higher-kinds-in-csharp-with-language-e...

louthy··on Monads in C# (Part 2): Result
In C# you can implement SelectMany for a type and that gives this:

    from id    in ParseId(inputId)
    from user  in FindUser(id)
    from posts in FindPostsByUserId(id)
    from res   in DeactivateDecision(user, posts)
    select res;
It is the equivalent to do-notation (was directly inspired by it). Here's an example from the language-ext Samples [1], it's a game of 21/pontoon.

> I wrote what you might call an acid test for monad implementations a while back: https://jerf.org/iri/post/2928/ It's phrased in terms of tutorials but it works for implementations as well; you should be able to transliterate the example into your monad implementation, and it ought to look at least halfway decent if it's going to be usable.

If I try to implement the test from your blog with Seq type in language-ext (using C#), then I get:

    Seq<(int, string)> minimal(bool b) =>
        from x in b ? Seq(1, 2) : Seq(3, 4)
        from r in x % 2 == 0
                      ? from y in Seq("a", "b") 
                        select (x, y)
                      : from y in Seq("y", "z")
                        select (x, y)
        select r;
It yields:

    [(1, y), (1, z), (2, a), (2, b)]
    [(3, y), (3, z), (4, a), (4, b)]

Which I think passes your test.

[1] https://github.com/louthy/language-ext/blob/main/Samples/Car...

louthy··on Monads in C# (Part 2): Result
Yes, that's the limitation until the value-type DUs arrive in C# 15.

In previous versions of language-ext, I defined Either as a struct with bespoke Match methods to pattern-match. But once pattern-matching appeared in C# proper, it didn't make sense to keep the struct type.

louthy··on Monads in C# (Part 2): Result
I think you're describing part of the bind function, which is part of the definition of the monad interface:

   a -> m b
But the full definition is:

   bind :: (a -> m b) -> m a -> m b
In C#, it would look like this:

   M<B> Bind(Func<A, M<B>> f, M<A> ma)
Assuming a future version of C# that supports higher-kinds that is.

In my language-ext library, I achieve a higher-kinded monad trait [1], like so:

    public interface Monad<M> : Applicative<M>, 
        where M : Monad<M>
    {
        static abstract K<M, B> Bind<A, B>(K<M, A> ma, Func<A, K<M, B>> f);
    }
Which is what the original comment is about. Most people in C# are not creating monads when they implement Bind or SelectMany for their type. They are simply making 'do-notation' work (LINQ). The monad abstraction isn't there until you define the Monad trait that allows the writing of any function constrained to said trait.

For example, a `When` function that runs the `then` monad when the `predicate` monad returns `true` for its bound value:

    public static K<M, Unit> When<M>(K<M, bool> predicate, K<M, Unit> then)
        where M : Monad<M> =>
        predicate.Bind(flag => flag ? then : M.Pure(unit));
This will work for any monad, `Option`, `List`, `Reader`, ... or anything that defines the trait.

So types like `Option` are just pure data-types. They become monads when the Monad trait is implemented for them. The monad trait can be implemented for data-types and function-types. Reader, for example, has the Monad trait implemented for the function: Func<E, A>

btw, monads also inherit behaviour from applicative and functor. The ability to lift pure values into the monad (a -> m a) is vital to making monads useful. This is `select` in LINQ, `pure` in Haskell's Applicative, and `Pure` in language-ext's Applicative [2].

[1] https://github.com/louthy/language-ext/blob/main/LanguageExt...

[2] https://github.com/louthy/language-ext/blob/main/LanguageExt...

louthy··on Monads in C# (Part 2): Result
Not discriminated unions, but they're coming (I think next version of C#). Although for now you can simulate them quite easily:

    public abstract record Either<L, R>;
    public sealed record Left<L, R>(L Value) : Either<L, R>;
    public sealed record Right<L, R>(R Value) : Either<L, R>;
Pattern-matching works well with these simulated algebraic data-types. Obviously, exhaustiveness checks can't work on 'open' types, so it's not perfect, but you can unpack values, apply predicate clauses, etc.

Other more niche features like type-providers don't exist either (although arguably those could be done with source-generators in C#). It's been a long time since I did any F#, so not sure if there's anything new in there I'm unaware of.

louthy··on Monads in C# (Part 2): Result
This is all very basic, instead you can use C#'s new static interface methods feature to create higher-kinded traits where you can properly generalise over a monad trait (or applicatives, functors, foldables, etc.), which is what I do in language-ext [0].

I'm not saying that implementing SelectMany for specific data-types isn't valuable. It certainly ends up with more elegant and maintainable code, but the true power of monads and other pure-FP patterns opens up when you can fully generalise.

* I have a blog series on it that covers implementing Semigroups, Monoids, Functors, Foldables, Traversables, Applicatives, Monads, and Monad Transformers (in C#) [1]

* The monad episode (my 'Yet Another Monad Tutorial') [2]

* An entire app generalised over any monad where the monad must support specific traits [3]. It's the program I use to send out the newsletters from my blog.

Happy to answer any questions on it.

[0] https://github.com/louthy/language-ext/

[1] https://paullouth.com/higher-kinds-in-c-with-language-ext/

[2] https://paullouth.com/higher-kinds-in-csharp-with-language-e...

[3] https://github.com/louthy/language-ext/tree/main/Samples/New...

louthy··on My role as a founder-CTO: year 8
> Personally I believe you’ve been operating on autopilot, and not designing your life to suit your own needs.

You have no idea about me at all, so please don't insult me by thinking that you do.

louthy··on My role as a founder-CTO: year 8
> Is it? So you can what? Buy exotic vehicles? Buy extra houses? Buy surgeries? Buy expensive experiences?

Regain your own time. As a former CTO who has recently exited, recovering my own time again is more valuable to me than the money (although the money means I can retain my own time going forward).

> His life has meaning, he’s of value to his employees and customers and partners.

Your work is not you and if you think that way, you're gonna be crushed when you come to retire. Even though I loved what I did for a career, it's better to do what you love for yourself, not "employees and customers and partners". Many people have other interests outside of building tech, but even if building tech is your only thing, exiting is a chance at starting something fresh and on your own terms.

louthy··on 'Three norths' alignment about to end
I've just bought a house in Alderwasley in Derbyshire, the nearest town is Wirksworth [1]. I assumed that, because this area was the heart of the industrial revolution [2], the town was an eponymously named workers town built for mill workers (there are actually entire towns in the area that were built for mill workers).

Then I read the history on wikipedia:

The name was recorded as Werchesworde in the Domesday Book of 1086 A.D. Outlying farms (berewicks) were Cromford, Middleton, Hopton, Wellesdene [sic], Carsington, Kirk Ireton and Callow. It gave its name to the earlier Wirksworth wapentake or hundred. The Survey of English Place-Names records Wyrcesuuyrthe in 835, Werchesworde in 1086, and Wirksworth(e) in 1536.

The toponym might be "Weorc's enclosure", or "fortified enclosure".

I just love how place names in the UK have evolved.

[1] https://en.wikipedia.org/wiki/Wirksworth

[2] https://en.wikipedia.org/wiki/Cromford_Mill

louthy··on 'Three norths' alignment about to end
> The title is written specifically for UK readers

Is it? The `.au` TLD might suggest otherwise.

louthy··on Hungry Fat Cells Could Someday Starve Cancer
I also found that after my first 3 day fast I was able to deal with hunger much better. I used to get irritable when hungry and now I realise I can just tolerate it without any real downside — even years after my last fast.

It’s like my brain has retrained itself to ‘just get over it’. It was quite something

louthy··on I stayed in a $40 capsule hotel (London)
I’m not claustrophobic, but looking at those pods makes me anxious. You’re one air con fuckup from asphyxiating on your own CO2 by the looks of it.
louthy··on Inverse Parentheses
I'm all for terseness in blog writing, but I think the author forgot to add the content. I know nothing more than I did when I opened it.
louthy··on TikTok Deal Is the Shittiest Possible Outcome, Making Everything Worse
Yet you link to a YouTube video of questionable provenance. Not one book reference.

Forgive me for just filing this in the ‘conspiracy theory nonsense’ folder.

louthy··on TikTok Deal Is the Shittiest Possible Outcome, Making Everything Worse
You said: “There's considerable evidence and reason to believe Washington invaded Afghanistan in 2001 to supercharge opium production”, yet you provide nothing to back up your claim. It is not trolling to point that out.

Your link to some stats on levels of poppy production does not support your conspiracy theory.

louthy··on TikTok Deal Is the Shittiest Possible Outcome, Making Everything Worse
> There's considerable evidence

Yet you provide none.

louthy··on How getting richer made teenagers less free
People with mental health issues need help and support. Just because there’s a pithy saying, doesn’t make it universally beneficial to have suffered hardship.

Not sure what else you’re expecting? I’m not advocating imposed hardship, just trying to give some context for why it can often lead to a more robust and driven person. It’s clearly not universally true.

I imagine there are lots of veterans that are able to cope and have become more robust. But there will always be mental health aftershocks, because that’s why it was a hardship in the first place.

louthy··on How getting richer made teenagers less free
As someone who has had some serious hardship and is certainly more resilient because of it, I can also confirm the mental scarring that comes as ‘part of the package’.

I think to an extent the mental impact of it is a necessary evil. The future resilience manifests as a drive to not find yourself in the same (or an equally difficult) position again — because it’s so emotionally devastating — so you fight harder to not allow it to happen again. This makes a person more driven in general.

Another aspect is that you’ve seen how ‘deep’ an emotion can be (traumatic) and so more ‘everyday’ emotional events can seem much more trivial, making them easier to deal with. Although, it can sometimes leave the person seeming ‘cold’ emotionally. One thing I found was I was less tolerant of people without the level of resilience I had, which I had to work on.

Of course, there will be some people that can’t endure the initial hardship and don’t develop that resilience. My impression is that most people do endure and find a way to come out of the other side, like a basic survival instinct, although that’s purely anecdotal.

louthy··on How getting richer made teenagers less free
It isn't about a particular time in history, it's about the individual. An individual who suffers hardships often has to endure to overcome said hardships. That makes the individual more resilient and more able to deal with future hardships.

I think the phrasing can come across as a bit macho, which I don't think is the point. It's about resilience.

louthy··on Germany: Amazon is not allowed to force customers to watch ads on Prime Video
> cancelling Amazon Prime at first, but realized I didn't -really- need some JIXFOZ branded gadgets next day, after all.

The problem with cancelling Prime is the unrelenting haranguing to re-sign up and the clearly punitive delivery charges. You get adverts from cancelling due to adverts and end up paying more.

I’ve just started to focus my purchases at specialist UK stores, rather than defaulting to Amazon for everything.

louthy··on Vibe coding creates fatigue?
> If your protection is to "understand the implementation" it means buggy code.

Hilarious. Understanding the code is literally the most important thing. If you don't understand the code then you can't understand any unit tests you write either. How could you possibly claim test coverage for something you don't understand?

I suspect you primarily develop code with dynamic languages where you're reinventing type-systems day-in day-out to test your code. Personally, I try to minimise the need for unit-tests by using well-defined types and constraints. The type-system is a much better unit-tester than any human with a poor understanding of the code.

← PreviousPage 5 of 34Next →