1

I have to write this Pearson Hash for school, but I never heard of it so it's difficult to imagine how it works. That is makes things more difficult that I learned haskell a long time ago and I almost forgot it.

Here is the thing: They gave me that the syntac of this function will be this:

pearsonHash :: [Int] -> [Int] -> Int

and the algorithm of Pearson Hash is:

h := 0
for each c in C loop
    index := h xor c
    h := T[index]
end loop
return h

They said, that: Let C be the input sequence of bytes, and h the value to be calculated. And the first parameter of pearson hash should a a predefined T list which contains a permutation of [0..255].

There are the test cases:

pearsonHash ([0..127] ++ [255,254..128]) [1..10]   ==  11
pearsonHash [255,254..0] [ ord c | c <- "Hello" ]  ==  189

I think they should be True.

This is just a part of the work (meaning this is only one function from a lot), so I don't want you to solve this instead of me, I just need help how to solve this function because I got stuck with this one.

Tair
  • 3,779
  • 2
  • 20
  • 33
  • 1
    A tip: If you indent lines by 4 spaces, they'll be marked as a code sample. You can also highlight the code and click the "code" button (with "{}" on it). – jub0bs Mar 16 '15 at 10:49
  • 1
    It is unclear what problem you have. Stack Overflow is not a tutoring site. Be more specific. –  Mar 16 '15 at 11:48

1 Answers1

4
h := 0
for each c in C loop
    index := h xor c
    h := T[index]
end loop
return h

OK, so this looks pretty imperative. When you see a loop like this, what you probably want to do is turn the "loop body" into a function, and then the loop itself will be either foldr or foldl. So your code ends up looking something like

hashStep :: [Int] -> Int -> Int -> Int
hashStep ts h c = ...???...

pearsonHash :: [Int] -> [Int] -> Int
pearsonHash ts cs = foldr (hash_step ts) 0 cs

Now, can you figure out what hashStep should do?

MathematicalOrchid
  • 61,854
  • 19
  • 123
  • 220
  • After a quick brainstorm I would say the hashStep function will lokk like this: hashStep :: [Int] -> Int -> Int hashStep ts h = ts!!(h xor c) | c <- ts But I have to think it through correctly and test it. I am sure I can figure it out on my own. Thanks for helping! – Bálint Csertán Mar 16 '15 at 15:19
  • @MathematicalOrchid didn't even look at the type signature.. thought you are suggesting a lambda and proposed a more obvious way :) – Tair Mar 16 '15 at 16:55
  • I got the answer! hashStep :: [Int] -> Int -> Int -> Int hashStep ts h c = ts!!(xor h c) Thanks a lot for the help again! – Bálint Csertán Mar 17 '15 at 17:50