I have read this page a few times, and have even started using this language feature in my project, but I still don't really get the concept.

Like, why should we actually use it? Right now, this looks like syntax sugar to me.

It doesn't help that my brain sees this as a quirky assignment...

I appreciate if anybody can simplify this concept to me.

Thank you in advance ๐Ÿ™

P.S. My experience with Gleam has been awesome so far. If its ecosystem could be a bit more mature, it would easily be my favourite programming language.

P.P.S. If it helps (with drawing parallels), I am most familiar with Python, followed by Javascript and Java, and have touched C, Dart, Kotlin and Rust some time back.

you are viewing a single comment's thread
view the rest of the comments
[โ€“] 6 points 3 days ago (1 child)

Yes, it's syntactic sugar that avoids the "marching pyramid of doom". You can see the difference in the example code from that page:

pub fn with_use() -> Result(String, Nil) {
  use username <- result.try(get_username())
  use password <- result.try(get_password())
  use greeting <- result.map(log_in(username, password))
  greeting <> ", " <> username
}

pub fn without_use() -> Result(String, Nil) {
  result.try(get_username(), fn(username) {
    result.try(get_password(), fn(password) {
      result.map(log_in(username, password), fn(greeting) {
        greeting <> ", " <> username
      })
    })
  })
}

The result is less indentation, and fewer braces, so less syntactic noise. Plus you don't have to figure out which closing brace is which when you make changes.

Regarding your comment I don't think I agree that it hides the underlying concept since the information is all still there: you swap out the fn keyword and a pair of braces for the use keyword, a left arrow. So if you know what you're reading use signals an inline function inside a call-site with an unusual argument notation.

Syntactically it's similar to the await keyword in JavaScript. (But use is much simpler - await conceptually conceals calls to .then). Before async/await the marching pyramid of doom was a common complaint about async javascript, especially from people offended by not being allowed to use threads.

The syntactic simplification also has a strong resemblance to Haskell's "do notation", complete with the left-arrow syntax. But like with await, do notation conceals calls to the bind operator (>>=) which is Haskell's version of flatMap / then.

  • source
  • hideshow 1 child comment