我对Haskell还比较新,尝试编写一个Scrabble求解器。它可以接收当前拥有的字母,找到所有排列,并过滤掉不在词典中的单词。代码非常简单:
import Data.List
main = do
dict <- readFile "words"
letters <- getLine
let dictWords = words dict
let perms = permutations letters
print [x | x <- perms, x `elem` dictWords]
然而,与我使用 Python 实现的非常相似的实现比较起来,速度极慢。是否有什么根本性的错误?
*编辑:这是我的 Python 代码:
from itertools import permutations
letters = raw_input("please enter your letters (without spaces): ")
d = open('words')
dictionary = [line.rstrip('\n') for line in d.readlines()]
d.close()
perms = ["".join(p) for p in permutations(letters)]
validWords = []
for p in perms:
if p in dictionary: validWords.append(p)
for validWord in validWords:
print validWord
我没有精确计时,但大致上感觉Python实现的速度是Haskell的两倍左右。也许我不该说Haskell的代码与Python相比是“极慢的”,但由于Haskell是静态类型语言,所以我认为它本应该比Python更快,而不是比Python还慢。
Text
和[Set
](https://hackage.haskell.org/package/containers)。为什么这个问题与等价的Python解决方案具有不同的性能特征非常有趣,如果您发布您的Python代码,那将有助于我们解决它。 - Ian Henry