2

So I'm trying to write a function which performs a input function f on input list ls [l1, l2, ..., ln] and output a string "[" ++ (f l1) ++ "," ++ (f l2) ++ "," ++ ... ++ (f ln) ++ "]"

flist :: (a -> String) -> [a] -> String
flist f ls = 

for example:

>flist show [1, 2, 3]

would output "[1, 2, 3]"

>flist (fun x -> x) ["dog"]

would output "[dog]"

I tried to use foldl'

flist f ls = "[" ++ (foldl' (++) f "," ls) ++ "]" 

which doesn't seems to be working

2 Answers 2

6

Hint:

  1. Produce [f x1,...,f xn] first, applying f to every member.
  2. Then, write a function that takes [y1,...,yn] and w and produces an interleaving [y1,w,y2,w,...,yn]. This can be done by recursion. (There's also a library function for that, but it's not important.)
  3. Compose both, to obtain [f x1, ",", ...] and then concatenate the result.
  4. Add brackets to the resulting string.
Sign up to request clarification or add additional context in comments.

Comments

5

How about this:

import Data.List

flist f list = "[" ++ (intercalate "," $ map f list) ++ "]"

intercalate puts Strings in between of other Strings, it is (in this case) a slightly configurable version of unwords.

Comments

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.