ceth
ceth

Reputation: 45285

Split string to substring

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

Answers (2)

wit
wit

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

DiegoNolan
DiegoNolan

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

Related Questions