0

I have a scheme function like so that generates a hash value for a given input

 (define hash
  (lambda (c)
    (cond
     ((null? c) 600)
     (else 
       (reduce + (map (lambda (x) (cv x)) c) (* 12 (hash (cdr c))))))))

cv(x) is where each letter maps to a number a = 1, b = 2, c = 3 ... z = 26.

600 is the base value. 12 is a unique number.

My problem is I'm doing something wrong that my values are a bit off and can't find where the problem relies.

Expected Output

(hash '(h i))
==> 86516

My Output

(hash '(h i))
==> 86525

This is what I'm trying to do :

600 * 12 + 9(val for i) = 7209 

then,

7209 * 12 + 8(val for h) = 86516

As you can see my values are a bit off, I suspect how I'm using the reduce function.

1 Answer 1

4

You have a recursion inside reduce, while reduce is a high level function. No.

A simple recursion will suffice:

(define hash
  (lambda (c)
    (if (null? c)
        600
        (+ (cv (car c)) (* 12 (hash (cdr c)))))))

(hash '(h i))  ; => 86516

If, on the other hand, you want to use a high level function, you could use either foldr, as in:

(define hash
  (lambda (c)
    (foldr (lambda (x y) (+ (cv x) (* 12 y))) 600 c)))

or foldl, as in:

(define hash
  (lambda (c)
    (foldl (lambda (x y) (+ (cv x) (* 12 y))) 600 (reverse c))))
0