4 ms·
A lot of people dislike the terseness of that style (especially the use of operators.) I'm not one of those people, but I can understand their point of view. Fo
by greydius 9y ago
A lot of people dislike the terseness of that style (especially the use of operators.) I'm not one of those people, but I can understand their point of view. Fortunately, Haskell also lets us write code in a way that managers can understand.
getCuteCat img = do
cropped <- findCat img
withTie <- addBowTie cropped
withSparkles <- makeEyesSparkle withTie
return (addRainbow (makeSmaller withSparkles))
- davidgay 9y agoHowever this style breaks down as soon as you have to do something more complicated than thread a single value, or have to do something more complicated than pass failures through.
- runeks 9y agoCode can always be broken up into simpler sub-components. The more you logically compartmentalize your code, the more it lends itself to these simple transformations. At the end of the day, you — not the problem you’re trying to model — decide how much you want to do in each function.
- haar 9y agoWe've been using this style a lot in Elixir via the `with` macro def get_cute_cat(image_id) do with {:ok, cropped} <- find_cat(image_id), {:ok, with_tie} <- add_bowtie(cropped), {:ok, with_sparkles} <- make_eyes_sparkle(with_tie) do with_sparkles |> make_smaller() |> add_rainbow() end end If any of the values on the rhs of a `<-` cannot be pattern matched, it returns up the returned value. This value can be pattern matched easily inside an `else` clause underneath the main block. The use of the `:ok,` vs `:error,` tuple convention allows multiple values to be destructured and passed around if needed (rather than an optional type). If you find the code getting unwieldily, as runeks said you can break it down into simpler constructs.
- runeks 9y agoAnd, with this translation, I hope everyone can see how exceedingly simple the >>= operator is: “take the return value of what’s to the left of me and deliver it as an argument to the function to the right of me”. (Nitpick: if we’re translating kccqzy’s example verbatim, the last line shouldn’t include return, since — as per his definition — addRainbow is monadic)