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)))))))
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 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
I am fairly new to Emacs but I know enough to be dangerous. I've built my .emacs file from scratch and now have it in an org file. I am now trying to take it to the next level and make my configuration more user friendly for myself.
I mostly use Emacs for writing. Books, blogs, screenwriting, etc. I am trying to create a function that will turn on multiple modes and add the settings on the fly.
For example, I use olivetti-mode when writing. It centers the text. Each time I have to adjust the olivetti-set-width. I thought I would get fancy and enable the spell checker and turn off linum-mode as well.
However, every time I try it I get the error:
Symbol's value as variable is void: my-writing
Can anyone explain what I am doing wrong? I've google-fu'd quite a bit but I clearly have a gap in my understanding of what I am doing.
#+BEGIN_SRC emacs-lisp
(defun my-writing ()
"Start olivetti mode, set the width to 120, turn on spell-check."
((interactive)
(olivetti-mode)
(setq olivetti-set-width . 120)
(flyspell-mode)
(global-linum-mode 0)))
(add-hook 'olivetti-mode-hook
(lambda () olivetti-mode my-writing t))
#+END_SRC
To disable global-linum-mode for specific major-modes, see automatically disable a global minor mode for a specific major mode
[Inasmuch as olivetti-mode is a minor-mode that is enabled subsequent to whatever major-mode is already present in the buffer, the original poster may wish to turn off linum-mode locally in the current buffer by adding (linum-mode -1) to the tail end of the function my-writing (see below). That idea, however, assumes that the original poster wanted to have linum-mode active in the current buffer just prior to calling my-writing.]
The function my-writing in the initial question contains an extra set of parenthesis that should be omitted, and the hook setting is not in proper form.
olivetti-set-width is a function that takes one argument, so you cannot use setq -- see function beginning at line 197: https://github.com/rnkn/olivetti/blob/master/olivetti.el setq is used when setting a variable, not a function.
Although flyspell-mode is generally buffer-local, it is a good idea to get in the habit of using an argument of 1 to turn on a minor-mode or a -1 or 0 to turn it off. When an argument is omitted, calling the minor-mode works as an on/off toggle.
Unless there are other items already attached to the olivetti-mode-hook that require prioritization or special reasons for using a hook with buffer-local settings, you do not need the optional arguments for add-hook -- i.e., APPEND and LOCAL.
There is no apparent reason to call (olivetti-mode) as part of the olivetti-mode-hook that gets called automatically at the tail end of initializing the minor-mode, so there is now a check to see whether that mode has already been enabled. The olivetti-mode-hook is being included in this example to demonstrate how to format its usage. However, the original poster should consider eliminating (add-hook 'olivetti-mode-hook 'my-writing) as it appears to serve no purpose if the user will be calling M-x my-writing instead of M-x olivetti-mode. The hook would be useful in the latter circumstance -- i.e., when typing M-x olivetti-mode -- in which case, there is really no need to have (unless olivetti-mode (olivetti-mode 1)) as part of my-writing.
#+BEGIN_SRC emacs-lisp
(defun my-writing ()
"Start olivetti mode, set the width to 120, turn on spell-check."
(interactive)
(unless olivetti-mode (olivetti-mode 1))
(linum-mode -1) ;; see comments above
(olivetti-set-width 120)
(flyspell-mode 1))
;; original poster to consider eliminating this hook
(add-hook 'olivetti-mode-hook 'my-writing)
#+END_SRC
lawlist's answer describes how you can go about doing what you're actually trying to accomplish, but the particular error you're getting is because Emacs Lisp (like Common Lisp, but not Scheme) is a Lisp-2. When you associate a symbol with a function using defun, it doesn't make the value of that symbol (as a variable) that function, it makes the function value of that symbol the function. You'll get the same error in a much simplified situation:
(defun foo ()
42)
(list foo)
The symbol foo has no value here as a variable. To get something that you could later pass to funcall or apply, you need to either use the symbol foo, e.g.:
(funcall 'foo)
;=> 42
or the form (function foo):
(funcall (function foo))
;=> 42
which can be abbreviated with the shorthand #':
(funcall #'foo)
;=> 42
You're getting the error because of:
(add-hook 'olivetti-mode-hook
(lambda () olivetti-mode my-writing t))
which tries to use my-writing as a variable, but it has no variable value at that point.
I have the following problem:
prolog prog:
man(thomas, 2010).
man(leon, 2011).
man(thomas, 2012).
man(Man) :- once(man(Man, _).
problem:
?- man(thomas).
true ; %i want only on true even if there are more "thomas" *working because of once()*
?- man(X).
X = thomas ; %i want all man to be listed *isn't working*
goal:
?- man(thomas).
true ;
?- man(X).
X = thomas ;
X = leon ;
X = thomas ;
I do unterstand why this happens, but still want to get the names of all man.
So my solution woud be to look if "Man" is initialized, if yes than "once.." else then... something like that:
man(Man) :- (->check<-,once(man(Man, _)); man(Man, _).
On "check" shoud be the code sniped that checks if the variable "Man" is filled.
Is this possible?
One way to achieve this is as follows:
man(X) :-
(nonvar(X), man(X, _)), !
;
man(X, _).
Or, more preferred, would be:
man(X) :-
( var(X)
-> man(X, _)
; once(man(X, _))
).
The cut will ensure only one solution (at most) to an instantiated X, whereas the non-instantiated case will run its course. Note that, with the cut, you don't need once/1. The reason once/1 doesn't work as expected without the cut is that backtracking will still come back and take the "or" condition and succeed there as well.
man(X) :-
setof(t,Y^man(X,Y),_).
Additionally to what you are asking this removes redundant answers/solutions.
The built-in setof/3 describes in its last argument the sorted list of solutions found in the first argument. And that for each different instantiation of the free variables of the goal.
Free variables are those which neither occur in the first argument nor as an existential variable – the term on the left of (^)/2.
In our case this means that the last argument will always be [t] which is uninteresting. Therefore the _.
Two variables occurring in the goal are X and Y. Or, to be more precise the variables contained in X and Y. Y is an existential variable.
The only free variable is X. So all solutions for X are enumerated without redundancies. Note that you cannot depend on the precise order which happens to be sorted in this concrete case in many implementations.
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