Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Haskell write a function to perform input function on list

Tags:

haskell

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

like image 249
penguindrum Avatar asked Nov 30 '25 15:11

penguindrum


2 Answers

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.
like image 151
chi Avatar answered Dec 02 '25 03:12

chi


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.

like image 29
Thilo Avatar answered Dec 02 '25 03:12

Thilo



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!