【问题标题】:Pearson Hash implementation in HaskellHaskell 中的 Pearson Hash 实现
【发布时间】:2015-05-18 10:49:28
【问题描述】:

我必须为学校编写这个 Pearson Hash,但我从未听说过它,所以很难想象它是如何工作的。这使得事情变得更加困难,我很久以前就学习了 haskell,我几乎忘记了。

事情是这样的: 他们告诉我这个函数的语法是这样的:

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

而Pearson Hash的算法是:

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

他们说:让C是输入的字节序列,h是要计算的值。 pearson hash 的第一个参数应该是一个预定义的 T 列表,其中包含[0..255] 的排列。

有测试用例:

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

我认为他们应该是True

这只是工作的一部分(意味着这只是很多功能中的一个),所以我不希望你代替我解决这个问题,我只需要帮助如何解决这个功能,因为我卡住了用这个。

【问题讨论】:

  • 提示:如果您将行缩进 4 个空格,它们将被标记为代码示例。您还可以突出显示代码并单击“代码”按钮(上面带有“{}”)。
  • 不清楚你有什么问题。 Stack Overflow 不是辅导网站。更具体。

标签: haskell hash pearson


【解决方案1】:
h := 0
for each c in C loop
    index := h xor c
    h := T[index]
end loop
return h

好的,所以这看起来非常必要。当你看到这样的循环时,你可能想做的是将“循环体”变成一个函数,然后循环本身将是foldrfoldl。所以你的代码最终看起来像

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

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

现在,你能弄清楚hashStep应该做什么吗?

【讨论】:

  • 经过快速的头脑风暴后,我会说 hashStep 函数会像这样: hashStep :: [Int] -> Int -> Int hashStep ts h = ts!!(h xor c) | c
  • @MathematicalOrchid 甚至没有看类型签名.. 以为您在建议 lambda 并提出了一种更明显的方法:)
  • 我得到了答案! hashStep :: [Int] -> Int -> Int -> Int hashStep ts h c = ts!!(xor h c) 再次感谢您的帮助!
猜你喜欢
  • 1970-01-01
  • 2011-05-13
  • 1970-01-01
  • 2010-10-17
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-04-02
  • 1970-01-01
相关资源
最近更新 更多