Pete Jodo
Pete Jodo

Reputation: 463

Scheme functions with lists

Let me begin with, I'm a beginner at scheme. Also this is based on HW so I'm not looking for an answer but an explanation of what's going on here. Here goes:

So I have a function that I need to implement which this much is given:

(define gen-hash-division-method
  (lambda (size)
    ...
  ))

Another function that I already implemented is defined as key and takes a word as a parameter and computes some value. It's correct so I won't post it but as an example key('(w o r d)) => 130293. Now all 'gen-hash-division-method' is supposed to do is just take the modulus of a key based on the parameter, in other words h(k) = k modulus size

The problem is, how am I supposed to compute that if k is not given as a parameter. This is how 'gen-hash-division-method' is meant to be used:

(define hash-1 (gen-hash-division-method 701))

701 I assume is the size parameter. And to test it, it looks like this:

(hash-1 '(h e l l o))

This is where I'm getting confused, I don't know what it's doing here. The word is given there but I don't understand how I'm supposed to call key('(h e l l o)) to get k to implement gen-hash-division-method(size) => k modulus size

Upvotes: 3

Views: 410

Answers (1)

Óscar López
Óscar López

Reputation: 236004

Let's see. gen-hash-division-method returns the modulus of a key based on the size parameter, but the characters that create the key will be passed later as another parameter, in other words:

(define gen-hash-division-method
  (lambda (size)
    (lambda (chars)
      (modulo (key chars) size))))

This is what's happening:

  • gen-hash-division-method is a function that, given a size, returns another function specialized for calculating keys modulo size
  • The returned function receives as parameter a list of characters
  • Once a list of characters has been passed, the key is calculated using the key procedure, afterwards the modulo operation is performed, always using the same size passed when creating the function

What we just implemented is an example of currying:

currying is the technique of transforming a function that takes multiple arguments (or a tuple of arguments) in such a way that it can be called as a chain of functions, each with a single argument (partial application)

As you can see, it works as expected:

; hash-1 calculates hashes modulo 701
(define hash-1 (gen-hash-division-method 701)) 

; in particular, here we find the hash modulo 701 for '(h e l l o)
(hash-1 '(h e l l o))

; any other list of chars we pass will be hashed modulo 701
(hash-1 '(f o o))

Upvotes: 2

Related Questions