penguindrum
penguindrum

Reputation: 65

Haskell write a function to perform input function on list

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

Upvotes: 2

Views: 76

Answers (2)

Thilo
Thilo

Reputation: 262474

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.

Upvotes: 5

chi
chi

Reputation: 116139

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.

Upvotes: 6

Related Questions