[英]How To Change List of Chars To String?
在 F# 中,我想将字符列表转换为字符串。 考虑以下代码:
let lChars = ['a';'b';'c']
如果我只是做lChars.ToString ,我会得到"['a';'b';'c']" 。 我正在尝试获取"abc" 。 我意识到我可能可以做一个 List.reduce 来获得我正在寻找的效果,但似乎库中应该内置一些原语来做到这一点。
为了对此提供一些上下文,我正在对字符串中的单个字符进行一些操作,完成后,我想显示结果字符串。
我试过用谷歌搜索这个,但没有任何乐趣。 我是否需要硬着头皮构建一个 List.reduce 表达式来进行这种转换,还是有一些更优雅的方法来做到这一点?
你有没有尝试过
System.String.Concat(Array.ofList(lChars))
在 F# 中有多少种方法可以构建字符串? 这是另一把:
let chars = ['H';'e';'l';'l';'o';',';' ';'w';'o';'r';'l';'d';'!']
//Using an array builder
let hw1 = new string [|for c in chars -> c|]
//StringBuilder-Lisp-like approach
open System.Text
let hw2 =
string (List.fold (fun (sb:StringBuilder) (c:char) -> sb.Append(c))
(new StringBuilder())
chars)
//Continuation passing style
let hw3 =
let rec aux L k =
match L with
| [] -> k ""
| h::t -> aux t (fun rest -> k (string h + rest) )
aux chars id
编辑:时间可能很有趣? 我将 hw1..3 变成了函数,并为它们提供了一个包含 500000 个随机字符的列表:
没看到这里,所以:
let stringFromCharList (cl : char list) =
String.concat "" <| List.map string cl
"" 只是一个空字符串。
FSI 输出:
> stringFromCharList ['a'..'d'];;
val it : string = "abcd"
编辑:
不喜欢这种语法回到这里,所以这里有一个更规范的功能:
['a'..'z'] |> List.map string |> List.reduce (+)
['a';'b';'c'] |> List.fold_left (fun acc c -> acc ^ (string c)) ""
编辑:这是完成任务的另一种有趣方式:
type t =
| N
| S of string
static member Zero
with get() = N
static member (+) (a: t, b: t) =
match a,b with
| S a, S b -> S (a+b)
| N, _ -> b
| _, N -> a
let string_of_t = function
|N -> ""
|S s -> s
let t_of_char c = S (string c)
['a'; 'b'; 'c'] |> List.map t_of_char |> List.sum |> string_of_t
遗憾的是,仅使用“零”成员扩展 System.String 不允许将 List.sum 与字符串一起使用。
编辑(回答 Juilet):是的,你说得对,左折叠很慢。 但我知道右折叠更慢:):
#r "FSharp.PowerPack"
List.fold_right (String.make 1 >> (^)) ['a';'b';'c'] ""
当然还有快速而简单的:
new System.String(List.to_array ['1';'2';'3'])
我使用 'sprintf' 在我看来更容易:
let t = "Not what you might expect"
let r = [ for i in "aeiou" -> i]
let q = [for a in t do if not (List.exists (fun x -> x=a) r) then yield a]
let rec m = function [] -> "" | h::t -> (sprintf "%c" h) + (m t)
printfn "%A" (m q)
以下解决方案对我有用:
let charList = ["H";"E";"L";"L";"O"]
let rec buildString list =
match list with
| [] -> ""
| head::tail -> head + (buildString tail)
let resultBuildString = buildString charList
[|'w'; 'i'; 'l'; 'l'|]
|> Array.map string
|> Array.reduce (+)
或作为其他人发布:
System.String.Concat([|'w'; 'i'; 'l'; 'l'|])
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.