Reputation: 99
In my homework, I want to write a function which adds a string to a list of strings, but I have no idea how to do it.
I thought it would be something like this:
AddToLS :: [String] -> String -> [String]
AddToLS ls s = (ls : s)
But this code doesn't even compile.
It should work like this:
AddToLS [] "one" =["one"]
AddToLS ["one"] "two" =["one","two"]
AddToLS ["one","two"] "there" =["one","two","there"]
Upvotes: 3
Views: 349
Reputation: 16224
You want to add an element of type string at the end, so, you can concat that element wrapped into a list and use the existing (++)
function:
(++) :: [a] -> [a] -> [a]
so you will have to take your element and put it inside a list, like this:
AddToLS ["one", "two"] "three"
will be:
["one", "two"] ++ ["three"]
but you can define your own concat
only for list of strings, as I can see, the arguments are flipped:
AddToLS :: [String] -> String -> [String]
addToLS = flip $ (++) . (:[])
that's equivalent to:
AddToLS :: [String] -> String -> [String]
addToLS ss s = ss ++ [s]
Upvotes: 5