first question:
Define a function that joins a list of lists together using a separator value.
the type definition should be like that:
intersperse :: a -> [[a]] -> [a]
The separator should appear between elements of the list, but should not follow the last element.
Your function should behave as follows:
ghci> :load Intersperse
[1 of 1] Compiling Main ( Intersperse.hs, interpreted )
Ok, modules loaded: Main.
ghci> intersperse ',' []
""
ghci> intersperse ',' ["foo"]
"foo"
ghci> intersperse ',' ["foo","bar","baz","quux"]
"foo,bar,baz,quux"
after some time i manage to solve it:
intersperse myChar lists
| lists == [] = ""
| otherwise = attach myChar lists
where attach myChar (x:[]) = x
attach myChar (x:xs) = x ++ (myChar : []) ++ attach myChar xs
but, as you see, it's without the type definition.
if i put the type definition above the function, i get an error.
why?
second question:
before i get to this solution, i want to put another guard in the list of guards.
this quard should be after the first guard.
i want to check if the lists variable has just one list in it, so i just return the lists variable.
but i can't do a guard like that(again, an error is come to life :-)):
| lists == (x:[]) = lists
and also this didn't work:
| lists == (_:[]) = lists
why why why ? :-).
after this i tried to make other guard:
| length lists == 1 = lists
but it also raised an error.
(by the way, i don't need those guards, because i found that the first pattern after the "where" keyword, is exactly what i want.
this is the pattern i mean:
attach myChar (x:[]) = x
but still, i want to understand why the quards i tried, didn't work. also, i found this solution, by luck, and i don't think everytime i will notice such a things :-)
thanks a lot :-).
p.s. this exercise is from the book real world haskell.