Functional variant of 'oneof' function in Racket

前端 未结 3 1665
终归单人心
终归单人心 2020-12-20 04:31

I have written following function to find if one and only one of 5 variables is true:

(define (oneof v w x y z)
  (or (and v (not w) (not x) (not y)  (not z         


        
3条回答
  •  旧时难觅i
    2020-12-20 04:45

    You can literally count how many true values you have in a list of arbitrary length, if that number is 1 then we're good (remember that in Scheme any non-false value is considered true). Also notice how to create a procedure with a variable number of arguments, using the dot notation:

    (define (oneof . vars)
      (= 1
         (count (lambda (v) (not (false? v)))
                vars)))
    

    For example:

    (oneof #f #f #f #f #t)
    => #t
    (oneof #f #f #f #f #f)
    => #f
    (oneof #t #t #t #t #t)
    => #f
    

提交回复
热议问题