Hacker News new | ask | show | jobs
by kingdomcome50 1775 days ago
I understand. But what is purpose of `Maybe`? The reason one would reach to the above construct is precisely to offload (pushing to later) the handling of a value that may (or may not) be present at runtime such that a developer can write code assuming the value is always present and ignore the `Nothing` case.

Sure you can unwrap it right away, but that isn't necessary because you could also just "bind" the next function call to the monad (which is more idiomatic to the construct). You never have to worry about that value in this case because... well... that's the benefit of using `Maybe`.

I'm not super familiar with Haskell, but my sense is that the author is trying more to please the compiler (at a specific point in the program!) than simplify the logic. That is, they want a concrete value (`configDirs`) to exist in the body of `main` more than they want the cleanest representation of the problem in code.

1 comments

> But what is purpose of `Maybe`?

In this case, it's to provide a better error message in case there's an empty list than `fromList` would provide.

> You never have to worry about that value in this case because... well... that's the benefit of using `Maybe`.

But you do, your entire program doesn't live in `Maybe` so at some point you have to check whether it's `Just a` or `Nothing`. Once again, the whole point of the post is to argue that getting out of the `Maybe` as close to parsing time as possible is preferable so you have a more specific type to work with after that. You also see right away what didn't parse instead of just knowing that something didn't parse, which is what would happen if you stayed in the `Maybe` monad for all your parsing.

> your entire program doesn't live in `Maybe`

Well... if your entire program is dependent on some input that may or may not exist at runtime... then it kind of does live in `Maybe`.

I have no issue with unwrapping a `Maybe` to throw an exception. But I do find it a bit ironic that the post is about parsing instead of validating, that the perfect construct is right there to exemplify how it could be done, but the author then chooses to eschew it and instead show examples of how validation could look.

The body of `main`, for example, could be refactored to something like:

    maybeInitialized <- (getConfigurationDirectories >>= head >> initializeCache)
Which actually shows how `Maybe` can be used to simplify the system. If you want to unwrap the maybe at this point to throw, go for it! But the above is a much cleaner representation of the program than what author is trying to do (it's crystal clear how the cache might get initialized). I would expect "Parse don't validate" to be about how useful `Maybe` is to combine parsing logic into a functional flow vs. how validation leads to an ugly procedural approach.