这段代码对我来说似乎有点迟钝......有人想通过解释来帮助我吗?
uniq_c l = [ nl (tam l) i s | (s,i) <- uniq_c' l]
tam = maximum . map snd . uniq_c'
uniq_c' [] = []
uniq_c' (h:t) = let (list,rest) = span (==h) t
n = length list + 1
in (h,n) : uniq_c' rest
nl tam n line = let l = length $ show n
l_tam = length $ show tam
n' = replicate (l_tam-l) " "
in concat n' ++ show n ++ " " ++ line
答案 0 :(得分:6)
那段代码不是很好。它不会重用任何现有的Haskell库。
这是另一种选择。 group
函数完成了工作;认识到重复发生。 length &&& head
获取每个这样的子列表并进行计数和单词。最后uniq_c
找到最大宽度,并使用printf
格式化输出。
import Control.Arrow
import Data.List
import Text.Printf
uniq :: (Eq a) => [a] -> [(Int, a)]
uniq = map (length &&& head) . group
uniq_c :: [String] -> [String]
uniq_c l =
let us = uniq l
width = length . show . maximum . map fst $ us
in map (uncurry $ printf "%*d %s" width) us
答案 1 :(得分:3)
uniq_c
提供字符串出现在与特定字符串空格连接的字符串列表中的次数:
*A> uniq_c ["The","quick","brown","fox","fox"]
["1 The","1 quick","1 brown","2 fox"]
*A> uniq_c $ ["The","quick","brown","fox","fox","fox"] ++ (replicate 100 "fox")
[" 1 The"," 1 quick"," 1 brown","103 fox"]
uniq_c'
提供了(string,count)
的元组列表。
tam
找到最大计数(这将是任何特定字符串的最后一次出现)。
nl
缩进计数,以使计数合理。
*A> mapM_ putStrLn $ uniq_c $ ["The","quick","brown","fox","fox","fox"] ++ (replicate 100 "fox")
1 The
1 quick
1 brown
103 fox