Hi, OCaml beginner here. I’m coming from Rust, which has some syntactic sugar/quality of life features around pattern matching and errors. I’m curious what the idiomatic equivalents are for OCaml?
Early return
Basically, if you have an error, you can return early:
let file = match fs::read("hello.txt") {
Ok(file) => file,
Err(err) => return Err(err)
};
let file = fs::read("hello.txt")?;
If I understand this thread correctly, there’s no easy way to do early return in OCaml. I suppose the simplest equivalent would be to use some combination of Result.bind
and |>
? Or let*
?
As an aside, this type checks because return
creates the type !
, i.e. the Never type, which indicates a computation that doesn’t finish.
If let
This is nice for situations where you need to match on a single pattern:
if let Ok(file) = fs::read("hello.txt") {
println!("opened file");
}
if let Ok(file) = fs::read("hello.txt") {
println!("opened file");
} else {
println!("failed!");
}
While let
Equivalent of if let
for loops.
while let Some(token) = lexer.next() {
process_token(token);
}
Let…else
Fairly new feature that lets you pattern match or do something that diverges, i.e. throw an error:
let Expr::Int(i) = parse() else {
return Err(anyhow!("expected an integer"))
}
todo!
If there’s a branch that you haven’t implemented but you need the code to type check, you can add todo!()
and it’ll compile (but panic at runtime):
match parse() {
Expr::Int(i) => handle_int(i),
_ => todo!(),
}
Thanks in advance for your help!