I have a few operations I want to thread where each can fail. I would much rather get the error as a value instead of using try-catch which breaks the flow of execution.
I can do the naive version and make my functions use nil as failure:
(if-let (op1 ...)
(if-let (op2 ...)
...
err1)
err2)
but this is nested and makes it harder to read.
I could use some-> which seems like the closest solution but it doesn't say what failed:
(if-let [res (some-> arg
op1
op2)]
res
somethin-failed) ;; what failed though?
I also looked at ->, and cond-> but they don't seem to help.
I know there are macros online to do these kind of things but I would much rather not add macros if something exists to solve this. Hopefully there is something of the form:
(some-with-err-> arg
op1 err1
op2 err2
...)
I may be overlooking something simpler, but I can't seem to find something built-in to address this issue.
I can write a macro to do it but would rather avoid it for now.
There's nothing built-in for this, but there are libraries for monadic error handling (e.g. Failjure) which seems like what you're looking for.
You could derive a version some-with-err-> from the some-> macro definition. The only practical difference is the map function that binds to steps now partitions the forms/error values, wraps step invocations in try and returns a namespaced map on failure:
(defmacro some-with-err->
[expr & forms]
{:pre [(even? (count forms))]}
(let [g (gensym)
steps (map (fn [[step error]]
`(if (or (nil? ~g) (::error ~g))
~g
(try (-> ~g ~step)
(catch Exception _# {::error ~error}))))
(partition 2 forms))]
`(let [~g ~expr
~#(interleave (repeat g) (butlast steps))]
~(if (empty? steps)
g
(last steps)))))
It can be used like some-> but each form must be accompanied by an error return value:
(some-with-err-> 1
(+ 1) :addition
(/ 0) :division
(* 2) :multiplication)
=> #:user{:error :division}
(some-with-err-> " "
(clojure.string/trim) :trim
(not-empty) :empty
(str "foo") :append)
=> nil ;; from not-empty
Related
I'm just building up a function at the REPL and ran into this.
I define a symbol S and give it a value:
(def S '(FRUIT COLORS (YELLOW GREEN) SKIN (EDIBLE INEDIBLE)))
I want, eventually, a function that takes the first entry in the parameter list and any and all subsequent parameter pairs and applies them to the first entry. I never got that far in my coding. I want to use a loop / recur construct (should I?), and here's how far I got in the REPL:
(loop [KV# (rest S)]
(if (empty? KV#)
nil
(
(pprint S, (first KV#), (second KV#))
(recur (rest (rest KV#)))
)
)
)
I get a "can only recur from tail position" compiler error.
After looking everywhere about this including 7 or 8 articles in Stack Overflow, I can only ask: Huh?!
I'm new at this. If recur isn't in the tail position, could someone please explain to me why?Something to do with 'if' statement syntax? GAHH! Clojure's not for the weak! Thank you.
You've made one of my favorite mistakes in Clojure - you've tried to use parentheses to group code. You need to use a (do ...) form to group forms together, as in:
(loop [KV# (rest S)]
(if (empty? KV#)
nil ; then
(do ; else
(pprint S, (first KV#), (second KV#))
(recur (rest (rest KV#)))
)
)
)
This gets rid of the "recur not in tail position" problem, but still fails - an arity exception on pprint - but I'll leave that for you to solve.
How did I spot this? My rule is that any time I find two left-parens together I immediately assume I've made a mistake and I need to figure out what I did wrong. In this case it was a little harder to spot because the left-parens were separated by intervening white space - but still, from the view of the lexical scanner they're adjacent to one another. So you just have to learn to think like a lexical scanner. :-)
I have a customizable variable timer-granularity used to increase/decrease the period of a timer each time the user calls something like (timer-faster) or (timer-slower). However, if the user sets timer-granularity to a negative number, then calling (timer-slower) will actually make the timer faster!
I'd like to constrain the value of this variable so that it is an error to try to set it to anything less than some threshold e.g.
(setq timer-granularity 0.3) ;; okay
(setq timer-granularity -1) ;; error!
Is this behaviour achievable?
You can setq anything to anything (whether sensible or not), but you can certainly add validation to the customize interface. e.g.:
(define-widget 'integer-positive 'integer
"Value must be a positive integer."
:validate (lambda (widget)
(let ((value (widget-value widget)))
(when (or (not (integerp value)) (<= value 0))
(widget-put widget :error "Must be a positive integer")
widget))))
(defcustom foo 1 "Positive int"
:type 'integer-positive)
You could add error handling to timer-faster and timer-slower -- but in this case I think I would simply trust that the user knows what they're doing if they're setting values in elisp.
For completeness: Emacs 26.1 did introduce add-variable-watcher which could be used to catch an 'invalid' setq, but I honestly don't think it's reasonable to use that for such a trivial purpose. The customize UI is the correct place to be asserting such things.
Similar to #phils's answer - you can do the same directly, without defining a new :type:
(defcustom foo 42
"Foo..."
:type '(restricted-sexp
:match-alternatives ((lambda (x) (and (natnump x) (not (zerop x)))))))
How you can have a different behaviour if a variable is defined or not in racket language?
There are several ways to do this. But I suspect that none of these is what you want, so I'll only provide pointers to the functions (and explain the problems with each one):
namespace-variable-value is a function that retrieves the value of a toplevel variable from some namespace. This is useful only with REPL interaction and REPL code though, since code that is defined in a module is not going to use these things anyway. In other words, you can use this function (and the corresponding namespace-set-variable-value!) to get values (if any) and set them, but the only use of these values is in code that is not itself in a module. To put this differently, using this facility is as good as keeping a hash table that maps symbols to values, only it's slightly more convenient at the REPL since you just type names...
More likely, these kind of things are done in macros. The first way to do this is to use the special #%top macro. This macro gets inserted automatically for all names in a module that are not known to be bound. The usual thing that this macro does is throw an error, but you can redefine it in your code (or make up your own language that redefines it) that does something else with these unknown names.
A slightly more sophisticated way to do this is to use the identifier-binding function -- again, in a macro, not at runtime -- and use it to get information about some name that is given to the macro and decide what to expand to based on that name.
The last two options are the more useful ones, but they're not the newbie-level kind of macros, which is why I suspect that you're asking the wrong question. To clarify, you can use them to write a kind of a defined? special form that checks whether some name is defined, but that question is one that would be answered by a macro, based on the rest of the code, so it's not really useful to ask it. If you want something like that that can enable the kind of code in other dynamic languages where you use such a predicate, then the best way to go about this is to redefine #%top to do some kind of a lookup (hashtable or global namespace) instead of throwing a compilation error -- but again, the difference between that and using a hash table explicitly is mostly cosmetic (and again, this is not a newbie thing).
First, read Eli's answer. Then, based on Eli's answer, you can implement the defined? macro this way:
#lang racket
; The macro
(define-syntax (defined? stx)
(syntax-case stx ()
[(_ id)
(with-syntax ([v (identifier-binding #'id)])
#''v)]))
; Tests
(define x 3)
(if (defined? x) 'defined 'not-defined) ; -> defined
(let ([y 4])
(if (defined? y) 'defined 'not-defined)) ; -> defined
(if (defined? z) 'defined 'not-defined) ; -> not-defined
It works for this basic case, but it has a problem: if z is undefined, the branch of the if that considers that it is defined and uses its value will raise a compile-time error, because the normal if checks its condition value at run-time (dynamically):
; This doesn't work because z in `(list z)' is undefined:
(if (defined? z) (list z) 'not-defined)
So what you probably want is a if-defined macro, that tells at compile-time (instead of at run-time) what branch of the if to take:
#lang racket
; The macro
(define-syntax (if-defined stx)
(syntax-case stx ()
[(_ id iftrue iffalse)
(let ([where (identifier-binding #'id)])
(if where #'iftrue #'iffalse))]))
; Tests
(if-defined z (list z) 'not-defined) ; -> not-defined
(if-defined t (void) (define t 5))
t ; -> 5
(define x 3)
(if-defined x (void) (define x 6))
x ; -> 3
I have this (not (some #(= (:length %1) 0) %)) as a postcondition. Written like this it's pretty clear, but when this condition isn't met I get this:
Assert failed: (not (some (fn* [p1__17852#] (= (:length p1__17852#) 0)) %))
Which isn't very readable. Is there a way to define the message for a postcondition, or for a precondition?
Edit 1:
Following noahlz and noisesmiths suggestion, (but using an external named function):
(defn not-zero-length
[evseq]
(not (some (fn [item] (= (:length item) 0)) evseq)))
(defn my-func
[evseq]
{:post [(not-zero-length %)]}
evseq)
(my-func '({:length 3}{:length 0}))
gives:
AssertionError Assert failed: (not-zero-length %)
Which is alot clearer.
This is discussed in the following clojure mailing list thread.
Looking at the clojure.core source you can see the fn macro only passes in a boolean to the assert function, and does not include an optional parameter for passing an additional message argument in.
So it looks like there is no way to do this cleanly yet.
This post in the same thread suggests the use of the clojure.test/is macro, which returns a meaningful error message.
(require '[clojure.test :refer [is]])
(defn get-key [m k]
{:pre [(is (map? m) "m is not a map!")]}
(m k))
(get-key [] 0)
returns
FAIL in clojure.lang.PersistentList$EmptyList#1 (form-init8401797809408331100.clj:2)
m is not a map!
expected: (map? m)
actual: (not (map? []))
AssertionError Assert failed: (is (map? m) "m is not a map!")
expanding on a suggestion above:
(not (some (fn zero-length [item] (= (:length item) 0)) %))
when you name an anonymous function, any errors involving that fn will be more readable
also, how is it that you have two % substitutions above? #() does not nest.
I'm trying to implement a try-catch block in scheme using (call-cc) method but i'm not sure how it can be used for that. I could not find any example.
And found examples contains just error-handling but what i want to do is: if an error occurred, the scheme program has to give a message to user (via display for-example) without suspending the program.
Is that possible?
Typically you'd use the with-handlers form. This lets you display an error message or take any other action before returning a value.
#lang racket
(define (foo x)
(with-handlers ([exn:fail? (lambda (exn)
(displayln (exn-message exn))
#f)])
(/ 1 x)))
(foo 1)
; 1
(foo 0)
; "/: division by zero"
; #f
If you really want to use a continuation directly for some reason, you could use call/ec for an error/escape continuation instead of the general call/cc.
Docs:
with-handlers
call/ec
Since you want to catch all errors, such as ones raised by both raise and raise-continuable you'd need both an exception handler (to deal with raised conditions) and an exit continuation (to avoid continuing with the try body). Simple syntax for try would be:
(import (rnrs base) ; define-syntax
(rnrs exceptions)) ; get `with-exception-handler`
(define-syntax try
(syntax-rules (catch)
((_ body (catch catcher))
(call-with-current-continuation
(lambda (exit)
(with-exception-handler
(lambda (condition)
catcher
(exit condition))
(lambda () body)))))))
This gets used as, for example:
> (try (begin (display "one\n")
(raise 'some-error)
(display "two\n"))
(catch (display "error\n")))
one
error
some-error # the return value.
Note: this is R6RS (and R7RS) Scheme.