I'm trying to learn Haskell and the mindset of programming functionally. I have started off by trying to understand the basics by writing code without any Monads
in it.
So far, I think I'm getting used to the type system and how the basics works.
I thought to myself, why not try to get some feedback on what I have written to learn even more. So hopefully I will get some valuable information!
I have written a function which iterates a String
and splits it into [String]
by using given Char
as a delimiter. Similar to what PHP's explode
and Python's split
does.
Here's what I have got so far:
main :: IO()
main = do
print $ groupBy "/hejsan/asdas" '/' []
print $ groupBy "/hejsan/asdas/hoho" '/' []
print $ groupBy "/hejsan/asdas/hahsdhashdas" '/' []
print $ groupBy "/hejsan/99/hahsdhashdas" '/' []
print $ groupBy "/123/asdas/hahsdhashdas///" '/' []
print $ groupBy "/123/asdas/hahsdhashdas//20////hej" '/' []
groupBy :: String -> Char -> [String] -> [String]
groupBy "" _ [] = []
groupBy (x:xs) c []
| x == c = groupBy xs c []
| otherwise = groupBy xs c [[x]]
groupBy "" _ (r:rs) = reverse result
where result = if r == "" then rs else [r] ++ rs
groupBy (x:xs) c (r:rs)
| x == c = groupBy xs c $ nextGroup ++ rs
| otherwise = groupBy xs c $ [r ++ [x]] ++ rs
where nextGroup = if r == "" then [r] else [""] ++ [r]
With output:
["hejsan","asdas"]
["hejsan","asdas","hoho"]
["hejsan","asdas","hahsdhashdas"]
["hejsan","99","hahsdhashdas"]
["123","asdas","hahsdhashdas"]
["123","asdas","hahsdhashdas","20","hej"]
So the main idea is to only show groups which have values in them. I bet there is:
- Some library function which can simplify the functions internals
- Some way to eliminate the 3rd argument so that it will be transparent to the user (Currying?)
I welcome all types of feedback except for feedback like "there is a library function which does all that for you". I'd like feedback on the internals and this particular problem is just an example