I’m trying to place a bunch of words into a hash table based on length. The words are stored in
data Entry = Entry {word :: String, length :: Int} deriving Show
Now, I’ve got all the words stored in “entries”, which is a list of Entry. Then, my hash table is defined as follows:
type Hash = [Run]
type Run = [Entry]
Now I’m trying to figure out how to get the entries into the hash table. The following is my current attempt
maxL = maximum [length e | e <- entries]
runs = [r | r <- [e | e <- entries, length e == i]] where i = [1..maxL]
Compiler’s obviously telling me that Int can’t be compared to [Int], but I don’t know how to say
e | e <- entries, e has length i
Any help is much appreciated!
Cheers
Your code is almost OK:
except that
wheredoesn’t work that way. It’s not a synonym forforeach; but forlet:So,
length eis an integer, butiis[1..maxL]which is a list of integers. You intended forito take on the values in[1..maxL]one-by-one, and that’s done by<-binding in list comprehension:Now,
[r | r <- xs]is the same as justxs, so it becomesWith “standard” functions, this is written as
It is also better algorithmically. Although, it won’t have empty runs for non-existent lengths, so the two aren’t strictly equivalent. But that can be fixed with another
O(n)pass over the results, with