0

I want a function that can turn an array into a string while inputting some new lines in there too.

Essentially let's say I have the list: [1234567890] I would like to pass that in with an integer and return that list as a String that is formatted like such:

(if the Int was 5, it would be)

"12345"
"67890"

I'm thinking I can do something like:

split :: Int -> [char] -> String
split n (x:xs) = split (take n-1 (x:xs)) -- I'm trying to make this recursive

I'm also going to assume that whatever length the array is will be divisible by the Int I pass in.

3
  • 2
    Unclear what you're trying to do. List of Char is already String (that's how String is literally defined), but your output example shows two strings, not one. Commented Apr 6, 2021 at 6:03
  • I would essentially just like to format the list. If there's a way to output 2 strings that'd be great, I was also thinking trying to push a \n char at the end of the length defined above. Commented Apr 6, 2021 at 6:07
  • I can't understand what is the intended output type: if you want to return exactly two strings, use .... -> (String, String). If you want to return many, use ... -> [String]. Commented Apr 6, 2021 at 7:26

1 Answer 1

2

To do this you have to make split recursive, but in your recursive step it did not receive the same number of parameters, and you tried to pass parts of the argument. The n can stay the same for every step, and when you take n out of the list in each step you also have to drop these n elements for the remaining steps.

splitN _ [] = ""
splitN n l = (take n l) ++ "\n" ++ (splitN n $ drop n l)
Sign up to request clarification or add additional context in comments.

5 Comments

This doesn't match the OP's type signature
@FyodorSoikin Right, just saw that after your comment on the question.
Alright, thanks I appreciate the comment! My output is looking like "12345\n67890" though. Do you have any additional ideas? The top of the split function looks like split :: Int -> [Char] -> [Char]
It looks like that because ghci just displays the \n character like that. You see that when you really print the output, formatted, e.g. putStrLn (splitN 5 "1234567890"). Now it really depends on what you want to do with it.
Ah, yes thank you @donttrythat I really appreciate your help!

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.