3

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"]
2
  • 1
    It seems that you want to add your new element x at the end of the list. In Haskell, it is much more efficient to add it at the beginning of the list, this is just expression (x:list). This is because the Haskell runtime system maintains only a pointer to the beginning of the list. Remember, lists can be unlimited, so in general you cannot maintain a pointer to the end of the list. Commented Nov 12, 2019 at 17:15
  • 1
    Appending to a list like this can produce a list that is very inefficient to iterate over. Consider using a different data structure (such as a difference list). Commented Nov 12, 2019 at 19:15

1 Answer 1

5

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]
Sign up to request clarification or add additional context in comments.

1 Comment

FWIW, I would not recommend the pointfree version to a beginner who does not know how to append an element to a list. The last one is shorter and obvious, the former required me to stop and think for a while.

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.