test.scm 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  1. (define-module (utils test))
  2. (use-modules
  3. ;; SRFI 64 for unit testing facilities
  4. (srfi srfi-64))
  5. (define-public approximately-equal?
  6. (lambda (value1 value2 epsilon)
  7. "Check whether two values are approximately equal by checking whether their
  8. difference is less than a given epsilon."
  9. (<= (abs (- (abs value1)
  10. (abs value2)))
  11. epsilon)))
  12. (define-public vectors-approximately-equal?
  13. (lambda (v1 v2 epsilon compare-proc)
  14. "Check whether all vector elements of vector v2 are approximately equal according to the
  15. compare-proc."
  16. (define compare-vector-elements
  17. (lambda (v1 v2 epsilon compare-proc)
  18. "Assume, that the length of both vectors is equal."
  19. (let ([num-elems (vector-length v1)])
  20. (let loop ([index 0])
  21. (cond
  22. [(< index num-elems)
  23. (if (compare-proc (vector-ref v1 index)
  24. (vector-ref v2 index)
  25. epsilon)
  26. (loop (+ index 1))
  27. #f)]
  28. [else #t])))))
  29. (cond
  30. [(= (vector-length v1) (vector-length v2))
  31. (compare-vector-elements v1 v2 epsilon compare-proc)]
  32. [else #f])))
  33. (define-public lists-of-vectors-approximately-equal?
  34. (lambda (l1 l2 epsilon compare-proc)
  35. "Check whether lists of vectors are approximately equal, by checking whether
  36. the vectors within the lists are approximately equal."
  37. (define (check-elements l1 l2 epsilon)
  38. (cond [(and (null? l1) (null? l2)) #t]
  39. [(compare-proc (car l1) (car l2) epsilon)
  40. (check-elements (cdr l1) (cdr l2) epsilon)]
  41. [else #f]))
  42. (if (= (length l1) (length l2))
  43. (check-elements l1 l2 epsilon)
  44. #f)))
  45. (define-public vector-set
  46. (lambda (a-vector pos value)
  47. "Update a vector in a functional way, returning a new vector, which is the
  48. same as the given vector, except that it has an updated value at position pos."
  49. (let ([vec-len (vector-length a-vector)])
  50. (let ([res-vec (make-vector vec-len)])
  51. (let iter ([index 0])
  52. (cond
  53. [(< index vec-len)
  54. (if (= pos index)
  55. (vector-set! res-vec index value)
  56. (vector-set! res-vec index (vector-ref a-vector index)))
  57. (iter (+ index 1))]
  58. [else res-vec]))))))