[英]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) ++ "]"
所以我正在尝试编写一个函数,它在输入列表
ls
[l1, l2, ..., ln]
上执行输入函数f
并输出一个字符串"[" ++ (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]"
输出
"[1, 2, 3]"
>flist (fun x -> x) ["dog"]
would output "[dog]"
输出
"[dog]"
I tried to use foldl' 我试过用foldl'
flist f ls = "[" ++ (foldl' (++) f "," ls) ++ "]"
which doesn't seems to be working 这似乎不起作用
Hint: 暗示:
[f x1,...,f xn]
first, applying f
to every member. [f x1,...,f xn]
,将f
应用于每个成员。 [y1,...,yn]
and w
and produces an interleaving [y1,w,y2,w,...,yn]
. [y1,...,yn]
和w
并产生交错[y1,w,y2,w,...,yn]
。 This can be done by recursion. [f x1, ",", ...]
and then concatenate the result. [f x1, ",", ...]
,然后连接结果。 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
. intercalate
将字符串放在其他字符串之间,它(在这种情况下) 是一个可轻微配置的unwords
版本 。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.