What is an idiomatic way to handle a bug in Racket?

I use OCaml, where I rely heavily on the result type along with a monadic interface to handle crashes in my applications. Exceptions exist in OCaml, but I rarely use them, except to work with the absence of the return keyword.

Is there such a trend in Racket (especially typical Racket)? What is the idiomatic way to handle and propagate crashes in Racket applications?

+5
source share
1 answer

There are several idioms:

exceptions

Exceptions are mainly used for errors, but sometimes for other kinds of "exceptional" situations.

  • (vector-ref "hello" 0) throws an exception because the string is not a vector
  • (string-ref "hello" 72) throws an exception because the index is out of bounds
  • (open-output-file "/does/not/exist") throws an exception if the path does not exist or cannot be opened due to permissions

result values

Some functions return a union in which the type acts as a variant of the data type. The result of X or false especially important.

  • (assoc 'a '((a . 1) (b . 2))) returns the pair (a . 1) , but
  • (assoc 'c '((a . 1) (b . 2))) returns false
  • (read-string 10) returns a string or a special eof if there are no characters before the end of the port

The cond => syntax can be useful for working with X or false results:

 (cond [(assoc key alist) => cdr] [else default-value]) 

continued failure

Some functions accept an additional (usually optional) argument that determines what happens when certain types of failures occur.

  • (hash-ref ht key) throws an error if ht does not contain an entry for key , but
  • (hash-ref ht key failure) either causes failure (if it is a procedure), or simply returns it (otherwise) if ht does not contain key
  • but (hash-ref not-a-hash-table key failure) throws a contract violation exception; it does not cause failure
+6
source

Source: https://habr.com/ru/post/1268671/


All Articles