Zulip Chat Archive

Stream: lean4

Topic: how to return early


Locria Cyber (Aug 26 2022 at 13:22):

I've been wanting to do something like this

  let Option.some start := cavesys.indexOf? start
  | .none => []

Jannis Limperg (Aug 26 2022 at 13:27):

Can be done, and you even have almost the right syntax already:

-- only works in a do block
let (some start) := cavesys.indexOf? start
  | return ...

Locria Cyber (Aug 26 2022 at 13:33):

What's return used for?

Locria Cyber (Aug 26 2022 at 13:33):

Can I use it inside match? I only want to return early for some branches

Jannis Limperg (Aug 26 2022 at 13:41):

return a is equivalent to pure a except that it early-returns (and is therefore a keyword). So if you want an early return in a match, you just do

match x with
| c1 => return y
| c2 => return z
| c3 => ...

For the particular case where you want to early-return from all branches except one, you can use the syntax I showed:

let (c3) := x   -- note the parentheses; they are required
  | a
b

This is equivalent to

match x with
| c3 => b
| _ => a

In my example above, I used return in the early-return statement a, but you can put any monadic action there. In particular, I could have used pure as well since the early-returniness of return does not come into play there.

Locria Cyber (Aug 26 2022 at 13:50):

oh, I use .some instead

Locria Cyber (Aug 26 2022 at 13:50):

No parentheses needed

Locria Cyber (Aug 26 2022 at 13:51):

Without ., binding might not be constructor

Locria Cyber (Aug 26 2022 at 13:51):

let .some cavesys := CaveSystem.fromLines? lines

Locria Cyber (Aug 26 2022 at 13:51):

thanks for your info

Jannis Limperg (Aug 26 2022 at 13:52):

Ah, this must be a recent change; I'm pretty sure the parentheses were required at some point. Thanks!

Locria Cyber (Aug 26 2022 at 15:29):

    let fold :=
      match line.take 1 |> Substring.toString with
      | "x" => FoldAt.left ?hole
      | "y" => ?hol
      | other => return ()

Locria Cyber (Aug 26 2022 at 15:29):

seems like I can't use return here

Sebastian Ullrich (Aug 26 2022 at 15:31):

You need a corresponding do for early return

Locria Cyber (Aug 26 2022 at 15:42):

    let fold <-
      match line.take 1 |> Substring.toString with
      | "x" => pure $ .left foldAt
      | "y" => pure $ .up foldAt
      | _other =>
        IO.eprintln s!"Invalid instruction: {line} ; {_other}"
        return none

I solved it


Last updated: Dec 20 2023 at 11:08 UTC