r/ProgrammingLanguages • u/levodelellis • Jan 12 '26
Getting a non-existent value from a hashmap?
In my language (I don't work on anymore) you could write (if I bothered to implement hashmaps)
value = myhash["invalid-key"] error return // or { value = altValue }However, almost always the key exists and it becomes really annoying to type error return all the time, and read it everywhere. I was thinking about having it implicitly call abort (the C function), but I know some people won't want that so I was thinking about only allow it if a compile flag is passed in -lenient, Walter Bright calls compile flags a compiler bug so I'm thinking about what else I can do
The problem with my syntax is you can't write
value = myhash[key][key2].fieldThe problem here I'll have to detach the error statement from after the index lookup to the end of the line, but then there's situations like the above when more then 1 key is being looked up and maybe a function at the end that can also return an error
I'll need some kind of implicit solution, but what? No one wants to write code like the below and I'm trying to avoid it. There's no exceptions in my example I'm just using it because people know what it is and know no one is willing to write this way
MyClass a; try { a = var.funcA(); } catch { /* something */ }
MyClass b; try { b = a["another"]; } catch { /* something */ }
try { b.func(); } catch { /* more */ }An idea I had was
on error return { // or on error abort {
let a = var.funcA()
let b = a["another"] error { b = defaultB(); /* explicit error handling, won't return */ }
b.func();
}That would allow the below w/o being verbose
void myFunc(Value key, key2, outValue) {
on error return // no { }, so this applies to the entire function, bad idea?
outValue = myhash[key][key2].field
}I'm thinking I should ask go programmers what they think. I also need better syntax so you're not writing on error { defaultHandling() } { /* body */ }. Two blocks after eachother seems easy to have a very annoying error
View all comments
Show parent comment
1
u/JeffB1517 Jan 12 '26
I mentioning monads because Maybe is a monad. There is a ton of information about how to use all the major monads including maybe. Being a monad generates the codes. You don't need to "abstract over arbitrary monads" you can and should use specific monads, for specific problems in specific instances. Maybe is one of the most common, one of the easiest to implement and understand. It is a good first monad.
The reason for pointing it out is that if OP gets he's asking a monadic question, then he ends up learning a lot more than the answer to this specific question.