简体   繁体   English

Haskell使用分隔符“ |”将字符串列表转换为字符串

[英]Haskell convert list of strings to string with divider “|”

How can I convert a list to string with divider "|", using foldl'? 如何使用foldl'将列表转换为带分隔符“ |”的字符串?

ltos :: String -> [String] -> String
ltos  []    = ""
ltos  (m:n) = foldl' f acc xs
   where
     f a b          = 
     acc            = 
     xs             = 

for example, 例如,

ltos ["a", "b", "c"]

would output 将输出

"a|b|c"

Here's a way: 这是一种方法:

foldl' (\acc x -> if (null acc) then acc ++ x else acc ++ "|" ++ x) [] ["a", "b", "c"]

The first time accumulator is empty, so just append the first string from the list. 第一次累加器为空,因此只需追加列表中的第一个字符串。 Thereafter, append the separator before the variable. 之后,将分隔符附加到变量之前。 If you run scanl , you can see the string being built as follows: 如果运行scanl ,则可以看到正在构建的字符串如下:

["","a","a|b","a|b|c"]

This is a cute combination of pattern matching and HOF. 这是模式匹配和HOF的可爱组合。

ltos :: [String] -> String
ltos []    = ""
ltos (m:n) = foldl' (\a b -> a ++ "|" ++ b) m n

You use the first element of the list as the starting string, then fold over the remaining elements (adding | between each of them). 您可以使用列表的第一个元素作为起始字符串,然后将其折叠在其余元素上(在每个元素之间添加| )。

(I'm assuming that you mistyped the signature to ltos ). (我假设您将签名输错了ltos )。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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