2

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.

1

2 Answers 2

3

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.

Sign up to request clarification or add additional context in comments.

Comments

3

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"]

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.