4 ms·
Hey, I have something similar in my (unpublished) language, even with the same character. However, the operator can appear anywhere within the body: while
by BoppreH 3y ago
Hey, I have something similar in my (unpublished) language, even with the same character. However, the operator can appear anywhere within the body:
while {
line: data.eat? "(.*)\n"
line: line.strip ()
print "We have read " + line
}
print "No more lines to eat."
The nice thing about it is that you're not limited to one conditional at the start of your "if"/"while" block. Have you ever a complex condition that's unwieldy to write in a single expression?
if (request.is_logged_in() && db.has_user(request.get_user_id()) && db.get_user(request.get_user_id()).authorize() && ...) {
// How do I refer to "user" now?
}
becomes
try {
user_id: request.get_user_id? ()
user: db.get_user? user_id
user.authorize? ()
print "Found user " + user.name
}, {
error UNAUTHORIZED
}
Which acts like a guard, without having to declare a new function. It can also replace the "walrus operator", nested try-catches, etc.
- FeepingCreature 3y ago`?` can do that in Neat, but you'd use a different mechanism where you mark some members of a return value as `fail` fields, which would then be error-propagated out of the entire function by `?`. Ie. `get_user_id` would return `(UserId | fail HttpError)`, and `get_user_id()?` would get you an expression that either yields `UserId` or returns `HttpError`. Then you could use a nested function to imitate your `try` block, or just map `HttpError` to whatever error you want with `case`. The thing about `?` being built on basic primitives is that you can always just decide to define your own sumtype error handling. Anyways, `:else` is more about "expected failures" than "errors". Loop-enders rather than process-enders.
- light_hue_1 3y agoYou can translate this directly to Haskell and it works as you would expect. You also have a lot of freedom on how to process the answer. catch (do user_id <- get_user_id <$> request user <- user_id . get_user <$> db.get_user authorize user print $ "Found user " <> user ^. name) (\e -> print "Error unauthorized) I don't want to say it.. but both this and Breakelse are rediscovering a basic use case of Monads :)
- FeepingCreature 3y agoSee over here: https://news.ycombinator.com/item?id=37889533 https://news.ycombinator.com/item?id=37889533 I am aware of Monads (they're explicitly called out in the article!), and specifically want to go in a different direction.