'Spliting a String in a List based on its characters
I am new to Haskell and also to Functional Programming. I came across an exercise(from my course) that I have a function String-> [String] that is being used to call any other function I have written in order to remove all the non-alphabetic characters. I have managed to do that,but if I were to call splitWord "I ne5ed help" I would get every character splited as an element ["I","n","e","e","d","h","e","l","p"],but I need to have an output List as that : ["I","ne","ed","help"]
This is my code :
splitword :: String -> [String]
splitword s = looplist s s
looplist :: String -> String -> [String] --loop through the string and create a list.
looplist (h:t) x
|((check [h]) == "" )= looplist t x --remove the "" added by check function.
|otherwise=[h] : looplist t x
looplist [] x = []
check :: [Char] -> [Char]
check x
| (x <= "z") && (x >= "a") = x
| (x <= "Z") && (x >= "A") = x
|otherwise = []
I am supposed to not use ONLY the where keyword,and only the basic operators(e.g for Lists :,+). No imports or any other built-in function.
As I said, I can use my check function to filter every letter,but my problem is that the output wouldn't be what I actually want. I am confused about how to actually fix that. Any suggestions?
Solution 1:[1]
I recommend making the problem easier for yourself: can you write a function that just does one split?
splitFirstNonAlpha :: String -> (String, String)
-- example calls:
-- splitFirstNonAlpha "ne5ed" = ("ne", "ed")
-- splitFirstNonAlpha "I ne5ed help" = ("I", "ne5ed help")
-- splitFirstNonAlpha " whoops a doodle" = ("", "whoops a doodle")
Once you have that, it should be much easier to call it in a loop correctly.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Daniel Wagner |
