157 points · by zzeder · 7y ago · 118 comments
Is it just me, or is this typical for all non-trivial Haskell code? I don't have any problems interpreting e.g. Clojure, or Javascript written in a functional style for that matter, but Haskell...
To read it quickly, you do have to learn & internalize abstractions. Both a common set of them (the usual type classes) & abstractions custom-built in your project. Abstractions in Haskell tend to be true abstractions & not encapsulations. You don't necessarily need to know the internals to understand the abstraction. I've seen this put off systems programmers before (people used to writing C etc and understanding the assembly).
I wouldn't expect someone with no Haskell knowledge to understand Haskell code. I've seen higher-level people (e.g. VPE-level) get upset by this and knee-jerk decide Haskell is problematic. I'm of the opinion that such knee-jerks aren't worth listening to..I don't care about opinions of people who haven't met (or honestly tried to meet) the prerequisites.
Regardless, I will say as someone who has learned Haskell: Once you learn it, it becomes so stupid easy to do everything. I feel like I can solve more complex problems faster & better in Haskell than other programming languages I have comparable (or more!) experience in.
Like a chat application is also multi-user real-time. It’s obvious that when a chat participant disconnects you hold onto the messages to deliver to them for later. When you disconnect from a Texas Hold’em online and you were small blind, what should you do? Wait? Shift the blinds over? The next player in line gets big or small? Copy the leading product’s behavior? It’s hard to reproduce all the states in someone else’s live, production game.
It’s not at all obvious and this logic has to live somewhere. It touches a bajillion things, like the raw connection state, timers, transient and long-term persistent state. Your programming language isn’t going to make it simpler for you. It can’t just hide in your database’s conflict resolution or some AWS service.
This is a great Haskell demo because it shows that you can’t hide this code anywhere. It stares back at you with all its ugliness.
i enjoyed your comment and these last two lines in particular. different programmers might interpret these lines in completely different ways: one as a critique of haskell for not being able to tidy the details away to make the code appear simpler, another as praise of haskell for making these mechanics explicit.
But since Haskell's ecosystem is small by comparison a lot of that logic leaks to your own application code. Especially when dealing with something like stateful websocket applications.
getSocketAPIPort :: Int -> IO Int
getSocketAPIPort defaultPort = do
maybeEnvPort <- lookupEnv "socketPort"
case maybeEnvPort of
Nothing -> return defaultPort
Just port -> maybe (return defaultPort) return (readMaybe port)
It gets a port from an environment variable, if it can, otherwise a default port. Conceptually, this is easy to understand, but translating your understanding of that process to Haskell is not 1 to 1. For example, the last line alone: Just port -> maybe (return defaultPort) return (readMaybe port)
You have to understand Maybe (and failure contexts), you have to understand that "return" does not return from a function like typical imperative languages, instead it wraps a type in a Monad (in this case, the IO Monad), and you also have to understand that most of those things on that line, including the "return" function, are parameters to the "maybe" function.There's a lot to understand in terms of the underlying machinery of Haskell to be able to read its cryptic flow and syntax. But it is worth it imo.
getSocketAPIPort :: Int -> IO Int
getSocketAPIPort defaultPort = do
maybeEnvPort <- lookupEnv "socketPort"
return . fromMaybe defaultPort $ maybeEnvPort >>= readMaybe
That's starting to border on over-terse, so you could expand the bind operator into do notation if you wanted to spread it out a bit further. On the other hand, it's also starting to feel over-verbose, using do notation for only a single IO action. Maybe... getSocketAPIPort :: Int -> IO Int
getSocketAPIPort defaultPort = fromMaybe defaultPort . (readMaybe =<<) <$> lookupEnv "socketPort"
That might be going too far. But maybe it's what I'd write. Just depends on how much I expect to make this more complicated in the future. This form has the simplest flow to read. I mean... it's dense. Really dense. But it has the fewest total things going on, and it neatly divides into three interesting parts, easily understood in isolation, plumbed together with two common combinators. But it's also pretty rigid in structure. If you ever want to add other sources for finding the port or change the priorities of them, that form would need to be totally rewritten, and probably would end up back in do notation.But in every case, all the various return calls should be combined into one (or none, if you use fmap or <$>), and the fallback to the default should only be written once.
getSocketAPIPort :: Int -> IO Int
getSocketAPIPort defaultPort = do
maybeEnvPort <- lookupEnv "socketPort"
return (fromMaybe defaultPort (readMaybe =<< maybeEnvPort))
Keeping the pattern match instead of using "fromMaybe" wouldn't be a bad idea, either: getSocketAPIPort :: Int -> IO Int
getSocketAPIPort defaultPort = do
maybeEnvPort <- lookupEnv "socketPort"
return (case readMaybe =<< maybeEnvPort of
Nothing -> defaultPort
Just port -> port)
It makes the default value stand out a bit more. return . fromMaybe defaultPort $ maybeEnvPort >>= readMaybe
Basically this is composing a function out of "return" and "fromMaybe" (using the composition operator "."), then partially applying defaultPort to that composed function, so you now have a function that takes one argument. The resulting function is then applied (using $) to the result of "maybeEnvPort >>= readMaybe".In "maybeEnvPort >>= readMaybe", ">>=" is an infix function that takes maybeEnvPort as its first argument (which is a Maybe Monad), "unpacks" it, applies "readMaybe" to the unpacked result. readMaybe returns another Maybe Monad.
The result of everything after the $ is a Maybe Monad that contains the port from the environment, or a failure condition. The result of applying the composed-and-partially-applied function (from before the $) to it is that the port from the environment is chosen if it didn't fail, otherwise the defaultPort is used, and then the whole thing is wrapped in an IO Monad.
"Convoluted and redundant" is in the eye of the beholder I guess
static IO<Integer> getSocketApiPort(@NotNull final Integer defaultPort) {
return lookupEnv("socketPort")
.flatMap((Optional<String> maybeEnvPort) -> {
if(!maybeEnvPort.isPresent()) {
return IO.of(defaultPort);
} else {
String strEnvPort = maybeEnvPort.get();
Optional<Integer> envPort = readMaybe(strEnvPort);
return IO.of(envPort.orElse(defaultPort));
}
});
} getSocketAPIPort :: Int -> IO Int
getSocketAPIPort defaultPort = do
maybeEnvPort <- lookupEnv "socketPort"
return $ case maybeEnvPort of
Nothing -> defaultPort
Just port -> fromMaybe defaultPort (readMaybe port)Elm is onto something with its obsession with simplicity and lack of features. I go back to old Haskell code and have to completely recredentialize in Haskell before I remember what's going on. I return to old Elm code and need very little ramp up.
I'm not making an "Elm > Haskell" argument, I just think experimentation with simplicity does this family of languages a favor.
I needed the explanation to understand what the code snippet was doing. Careful with those generalisations.
But since Elm is a DSL it can afford to cap the abstraction somewhere whereas Haskell is perhaps built for more complex problems than just a client facing web UI.
Having learned both, I feel the abstraction level is capped too low on Elm, sadly.
getSocketAPIPort :: Int -> IO Int
getSocketAPIPort defaultPort =
fromMaybe defaultPort <$> runMaybeT do
envPort <- MaybeT $ lookupEnv "socketPort"
MaybeT $ return $ readMaybe envPort def getSocketAPIPort(defaultport):
try:
return os.environ["socketPort"]
except KeyError:
return defaultport getSocketAPIPort :: Int -> IO Int
getSocketAPIPort defaultPort = readWithDefault <$> lookupEnv "socketPort"
where
readWithDefault mbPort = fromMaybe defaultPort $ readMaybe =<< mbPort readEnv :: Read a => String -> IO (Maybe a)
readEnv var = (readMaybe =<<) <$> lookupEnv var
Then the function in question becomes much easier (and probably unnnecessary too): getSocketAPIPort defaultPort = fromMaybe defaultPort <$> readEnv "socketPort"People say this about every single programming language.
Then perhaps you should fix these before indicting the code?
Haskell isn't just a different language to learn because it's different, it's also a different language because it has a community that values math-driven models of things. As such, you're going to end up at a disadvantage trying to understand every aspect of it without any prior consideration.
Sorta like how templates often baffle new programmers but are considered absolutely essential by folks who get a year or three of C++ experience.
It's not just you, I came here to say the same thing. I just feel dumb when I try to read Haskell, though I've been using Clojure in production for over 5 years.
With all pros (e.g. local reasoning, referential transparency, no destructive updates) and all cons (e.g. tons of marshalling/converting, piles of imports, shitty records) aside for a moment, I think you learn to read Haskell like you learn to read any other programming language: by writing a lot of it.
I suggest you first read through something that teaches you the basics like "Learn You a Haskell" or similar.
In a way, the experience is more like Clojure than Javascript. If you've read a Java-like language before, figuring another one tends to be easy. But if you've never read a Lisp-like, all the Java-like experience in the world won't help you to read a non-trivial Lisp program. You will just see some weird parentheses and won't be able to make head or tails of it.
Haskell is similar. Some upfront learning is needed before reading non-trivial programs.
I'd say 50% of the reason it's hard to read is you are not familiar and 50 hours of learning Haskell would sort that out. Training your visual memory to get used to (f a b) rather than f(a,b) etc. I liked to add redundant parens in my play code just to help me with this.
The other 50% is those damn library authors and their love of funny operators and advanced GHC extensions. And also some people like to play code golf with "point-free" style where instead of the x -> f x you'd just use f.
Which if taken to the extreme produces hard to read code that is lovingly called "pointless".
Code golf in Haskell is rife. I really prefer longAndMeaningfulVariableNamesThatErrOnTheSideOfBeingTooLong, but the Haskell culture isn't that way, and they prefer names like: s'.
Please don't just make things up.
The stuff you compose tend to be small functions that are easy to test & reason about.
The nice thing about composition in Haskell is that if you have correct program A & B, then the composition of A & B is also correct & easy to reason about.
https://github.com/Gabriel439/post-rfc/blob/master/sotu.md
There are a number of things where haskell is best in class and a larger number of things where it's immature. The language itself could be excellent at far far more than it is today, but libraries are limited for many tasks.
For instance, you could make a video game in Haskell. It has SDL2 bindings, plenty of networking libraries, best-in-class support for DSLs (user scripting), and you can even write the music for your game itself in Haskell!
Edit: only thing missing is PureScript on the frontend ;)
0 - https://en.wikipedia.org/wiki/Mental_poker 1 - https://github.com/cretz/go-mental-poker
Every once in a while I try going through the editor setups in this chart - https://github.com/rainbyte/haskell-ide-chart. But I run into lots of friction in any one I try. Between using the REPL, getting harmony in the project libraries and the IDE engine libraries, and learning a new editor, I run out of energy to also learn the language ecosystem (libraries, concepts, idioms, package managers).
An IDE that that surfaced everything the language encodes seems like it would lower the learning curve of Haskell. And every year it seems a little closer. Is there anything close to a jetbrains/visual studio/xcode yet?
It seems like all the type safety would be valuable enough that companies would pay for/invest in the ecosystem. Learning the ecosystem has been more challenging than learning the language at this point for me.
Things were not always this way. Just a few years ago, it was a bad experience, so if you have bad memories, it may be time to try again.
(add-hook 'haskell-mode-hook 'turn-on-haskell-indentation)
It is also not compatible with older versions of intero and haskell-mode, so if you have old configuration there, you may want to remove it.Honestly, it's even weird this isn't on by default.
From time to time a web browser to search a function in hoogle [1] and ghci (the interpreter console) to interactively try something out.
Honestly, I come to the conclusion, that at least for Haskell I do NOT need an IDE. I would need it for Java and other imperative languages that have huge libraries.
Haskell is one of the languages where it is a better investment of learning the language that spending time searching a good IDE.
Otherwise you can also integrate a language server with Vim or Emacs.
My pick is Kate on KDE. But I've been using vscode as well so I'm not tied to OSs that can run Kate.
Add in ghcid for continuous builds and it's almost ideal.
Is this project still active? Are there some features you'd like help developing?
For once again, thank you mate! +1
https://github.com/soupi/haskell-study-plan#a-few-cool-open-...