列表中出现次数的映射

时间:2015-03-20 18:02:40

标签: haskell substring find-occurrences

我正在使用这种类型的列表:

data Elem = Dot | Star

我将打印一个元组列表,其中包含2个单元,其中第一个表示列表中“Star”序列的长度,第二个列出了此序列出现的位置(第一个位置是1)。可能没有使用内置功能。<​​/ p>

功能是:

occ :: [Elem] -> [(Int, [Int])]

编辑: 我的想法是:将问题分成两个函数,一个用于查找每个“星”的位置,一个用于列出位置。

EDIT2: 示例:

occ [Dot,Star,Dot,Star,Dot,Star,Star,Star]

[(1,[2,4]), (3,[6])]

EDIT3: http://pastebin.com/uvvXBARL

1 个答案:

答案 0 :(得分:0)

我为复杂性道歉,但这项工作:

import Data.List
data Elem = Dot | Star
occ :: [Elem] -> [(Int, [Int])]
occ list = reduce (occ_hlp list 1 0 0 [])

-- Help function, which find all subsequence of Stars
occ_hlp [] pos cur_pos cur_len result       | cur_len == 0 = result
                                            | otherwise = ((cur_len, [cur_pos]):result)
occ_hlp (Star:t) pos cur_pos cur_len result | cur_len == 0 = occ_hlp t (pos + 1) pos 1 result
                                            | otherwise = occ_hlp t (pos + 1) cur_pos (cur_len + 1) result
occ_hlp (Dot:t) pos cur_pos cur_len result  | pos == 1 = occ_hlp t (pos + 1) 0 0 result
                                            | otherwise = occ_hlp t (pos + 1) 0 0 ((cur_len, [cur_pos]) : result)

-- Reduce obtained subsequence of Stars with same length                                            
reduce list = filter (\x -> not $ (snd x) == []) 
                 $ [(elem, sort $ foldl (\x y -> x ++ (snd y)) [] (filter (\x -> (fst x) == elem) list)) | elem <- [1..max_len]] 
                     where max_len = maximum $ map (fst) list

在这个程序中,我有2个帮助功能:

1)occ_help,它找到Stars的所有[(Int,[Int])]子序列。 以你的例子:

occ_hlp [Dot,Star,Dot,Star,Dot,Star,Star,Star] 1 0 0 []

将返回子序列列表:

[(3,[6]),(1,[4]),(1,[2])]

2)reduce,将这些元素的列表折叠到所需列表 例如:

reduce [(3,[6]),(1,[4]),(1,[2])]

将返回您的结果:

[(1,[2,4]),(3,[6])]
相关问题