functions: Add apply-tbf and apply-tbf/boolean.

This commit is contained in:
Sergiu Ivanov 2020-06-11 00:27:11 +02:00
parent dc3a0072a2
commit 2ed5f84338

View file

@ -31,7 +31,9 @@
[random-boolean-function/list (-> number? procedure?)] [random-boolean-function/list (-> number? procedure?)]
[tbf-w (-> tbf? (vectorof number?))] [tbf-w (-> tbf? (vectorof number?))]
[tbf-θ (-> tbf? number?)] [tbf-θ (-> tbf? number?)]
[vector-boolean->01 (-> (vectorof boolean?) (vectorof (or/c 0 1)))])) [vector-boolean->01 (-> (vectorof boolean?) (vectorof (or/c 0 1)))]
[apply-tbf (->* (tbf?) #:rest (listof (or/c 0 1)) (or/c 0 1))]
[apply-tbf/boolean (->* (tbf?) #:rest (listof boolean?) boolean?)]))
(module+ test (module+ test
(require rackunit)) (require rackunit))
@ -245,3 +247,33 @@
(module+ test (module+ test
(test-case "boolean->0-1" (test-case "boolean->0-1"
(check-equal? (vector-boolean->01 #(#t #f #f)) #(1 0 0)))) (check-equal? (vector-boolean->01 #(#t #f #f)) #(1 0 0))))
;;; Applies the TBF to its inputs.
;;;
;;; Applying a TBF consists in multiplying the weights by the
;;; corresponding inputs and comparing the sum of the products to the
;;; threshold.
(define (apply-tbf tbf . inputs)
(any->01
(>
;; The scalar product between the inputs and the weights
(for/sum ([x (in-list inputs)]
[w (in-vector (tbf-w tbf))])
(* x w))
(tbf-θ tbf))))
(module+ test
(test-case "apply-tbf"
(define f1 (tbf #(2 -2) 1))
(check-equal? (tabulate/01 (λ (x y) (apply-tbf f1 x y)))
'((0 0 0) (0 1 0) (1 0 1) (1 1 0)))))
;;; Like apply-tbf, but takes Boolean values as inputs and outputs a
;;; boolean value.
(define (apply-tbf/boolean tbf . inputs)
(01->boolean (apply ((curry apply-tbf) tbf) (map any->01 inputs))))
(module+ test
(define f1 (tbf #(2 -2) 1))
(check-equal? (tabulate/boolean (λ (x y) (apply-tbf/boolean f1 x y)))
'((#f #f #f) (#f #t #f) (#t #f #t) (#t #t #f))))