2

我想创建将字符串拆分为子字符串列表的函数,其中每个子字符串的长度为 k:

*Main> split_string_to_kmers "some_text" 3
["som","ome","me_","e_t","_te","tex","ext"]

这是我的解决方案:

split_string_to_kmers s k = split_string_to_kmers_helper s k []
    where split_string_to_kmers_helper [] k acc = acc
          split_string_to_kmers_helper s  k acc
            | length s >= k = split_string_to_kmers_helper (tail s) k (acc ++ [(take k s)])
            | otherwise = acc

我只是想知道是否有一种方法可以重写我的代码,这样它就会更加具体化。

4

2 回答 2

3

我想这有点不同。

import Data.List (tails)

mySplit :: String -> Int -> [String]
mySplit str k = filter (\s -> length s == k) $ map (take k) (tails str)

您可以通过组合过滤器和地图来提高效率。但这取决于你。

于 2013-10-31T19:49:53.717 回答
3

接下来是简单的解决方案(不是相同的列表尾部):

import Data.List.Split(chop)

splitRepN n = chop (\xs -> (take n xs,tail xs))

我们有下一个结果:

> splitRepN 3 "some_text"
["som","ome","me_","e_t","_te","tex","ext","xt","t"]

我们剪短尾巴以获得完整的解决方案:

splitRepN' n = takeWhile ((== n). length) . splitRepN n

> splitRepN' 3 "some_text"
["som","ome","me_","e_t","_te","tex","ext"]
于 2013-10-31T19:51:50.213 回答