help-gnu-emacs
[Top][All Lists]
Advanced

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

RE: [External] : Re: Function that changes value of a variable


From: wilnerthomas
Subject: RE: [External] : Re: Function that changes value of a variable
Date: Mon, 22 Aug 2022 01:18:31 +0200 (CEST)

Aug 21, 2022, 13:47 by drew.adams@oracle.com:

>> (defun constrain (variable min-n max-n)
>>   (cond
>>    ((< (symbol-value variable) min-n)
>>  (set variable min-n))
>>    ((> (symbol-value variable) max-n)
>>  (set variable max-n))
>>    ((eq (symbol-value variable) t)
>>  (set variable 1))
>>    ((eq (symbol-value variable) nil)
>>  (set variable 0))))
>>
>
> 1. Evaluate the initial value just once - bind
>  a local variable.
> 2. Make obvious to readers that the function
>  always sets the var (if numberp, t, or nil)
>  - put the `set' on the outside.
>
> (defun constrain (variable min-n max-n)
>  (let ((val  (symbol-value variable)))
>  (when (or (numberp val) (memq val '(nil t))) 
>  (set variable (if (numberp val)
>  (if (< val min-n)
>  min-n
>  (min max-n val))
>  (if val 1 0))))))
>
> 3. Your function doesn't change the value, if
>  if not a number, t, or nil.  Is that what
>  you really want?  If not:
>
> (defun constrain (variable min-n max-n)
>  (let ((val  (symbol-value variable)))
>  (unless (or (numberp val) (memq val '(nil t)))
>  (error "Oops?! `%s' is %S" variable val))
>  (set variable (if (numberp val)
>  (if (< val min-n)
>  min-n
>  (min max-n val))
>  (if val 1 0)))))
>
Function 3   is a very good function.  Thank you so very much for it.
I want to use in a function that requires a numeric value, but should
a user make a mistake by setting `t' on `nil', I can determine his likely
intention.

You do not modify the variable value when the input fall outside the
categories (numeric, t and nil).  Is that because we do not want to wreck
values can could well be other elisp structures (e.g. strings, lists, symbols).
Am I correct?








reply via email to

[Prev in Thread] Current Thread [Next in Thread]