2014-11-06 16 views
1

我想使用交互作用,它返回最常用的單詞和它出現的時間#的Haskell程序。我已經看到了排序的例子 - 但我不需要知道所有單詞的計數,我只需要最重複的單詞。到目前爲止,我有:哈斯克爾 - 計數列表中最重複的元素與交互

import Data.List -- (sort) 
import Data.Char -- (isAlpha, toLower) 
import Data.Ord -- (maximumBy) 

main = 
    interact 
    $ unwords 
    -- comment: here show the size of the list and the word (probably head) 
    . maximumBy(comparing length) 
    . group 
    . sort 
    . words 
    . map (\char -> if isAlpha char then toLower char else ' ') 

以上編譯。 maximumBy給出了最常用的詞是這樣的:

[the, the, the, the, the, the, the, the...] 

"the"出現在文本字的次數;我已經驗證"the"是我提供的文本中最常用的詞。

我想輸出是這樣的:"the, 318"

我試過只給第一個字母「t」和3如下:

import Data.List -- sort 
import Data.Char -- isAlpha, toLower 
import Data.Ord -- maximumBy 

main = 
    interact 
    $ unwords 
    . map (\(n, w) -> show n ++ ", " ++ show w) 
    . map (\s -> (length s, head s)) 
    . maximumBy(comparing length) 
    . group 
    . sort 
    . words 
    . map (\char -> if isAlpha char then toLower char else ' ') 

這給輸出:

"3, 't' 3, 't' 3, 't' 3, 't' ..." 

任何人都知道我在做什麼錯了?

回答

1

map (\s -> (length s, head s))map意味着該函數\s -> (length s, head s)被施加到每個"the"而不是到的"the"的列表中,反覆給予的長度和"the"第一個字符。因此刪除map應該會更好。您還需要修復了最後兩個步驟(除去unwordsmap):更有效地

$ (\(n, w) -> show n ++ ", " ++ show w) 
    . (\s -> (length s, head s)) 
    . maximumBy(comparing length) 

,你可以在管道比最大,它允許你

早期申請 map (\s -> (length s, head s))
  1. 避免在每個比較重新計算length最大功能做的
  2. 使用只是普通maximum代替maximumBy。 (這可以是其中如果有兩個同樣頻繁的人選擇了字略有不同,因爲它然後比較實際的字符串。)

換句話說,你可以使用

$ (\(n, w) -> show n ++ ", " ++ show w) 
    . maximum 
    . map (\s -> (length s, head s)) 

或者把它放在一起:

import Data.List (group, sort) 
import Data.Char (isAlpha, toLower) 

main = 
    interact 
    $ (\(n, w) -> show n ++ ", " ++ show w) 
    . maximum 
    . map (\s -> (length s, head s)) 
    . group 
    . sort 
    . words 
    . map (\char -> if isAlpha char then toLower char else ' ') 

還請注意我如何改變import語句中使用顯式命名要導入的官方語法。我強烈建議您不要使用評論,因爲這實際上給了我錯誤消息,指出您錯過了一個功能(group),並且您錯誤地列出了一個(maximumBy)模塊。

+0

感謝您的幫助。這是我想要的解決方案。 – Zorkolot 2014-11-06 11:48:20