Reputation: 45285
I want to create function that split string to list of substrings where each substring have length of k:
*Main> split_string_to_kmers "some_text" 3
["som","ome","me_","e_t","_te","tex","ext"]
Here is my solution:
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
I am just wondering if there is a way to rewrite my code so it will be more haskell specific.
Upvotes: 2
Views: 1248
Reputation: 1622
Simple solution is next (not the same tail of list):
import Data.List.Split(chop)
splitRepN n = chop (\xs -> (take n xs,tail xs))
And we have next results:
> splitRepN 3 "some_text"
["som","ome","me_","e_t","_te","tex","ext","xt","t"]
And we cut short tails for full solution:
splitRepN' n = takeWhile ((== n). length) . splitRepN n
> splitRepN' 3 "some_text"
["som","ome","me_","e_t","_te","tex","ext"]
Upvotes: 3
Reputation: 3766
I guess this slightly different enough.
import Data.List (tails)
mySplit :: String -> Int -> [String]
mySplit str k = filter (\s -> length s == k) $ map (take k) (tails str)
You could make this more efficient by combining the filter and the map. But that is up to you.
Upvotes: 3