简体   繁体   English

Haskell编写一个函数来执行列表上的输入函数

[英]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: 暗示:

  1. Produce [f x1,...,f xn] first, applying f to every member. 首先产生[f x1,...,f xn] ,将f应用于每个成员。
  2. Then, write a function that takes [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. 这可以通过递归来完成。 (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. 组合两者,获得[f x1, ",", ...] ,然后连接结果。
  4. Add brackets to the resulting string. 在结果字符串中添加括号。

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM