将元组序列写入CSV文件F# [英] Write a sequence of tuples to a csv file f#
问题描述
我试图将一组元组写入一个csv,但是普通的File.WriteAllLines被一组元组所重载.
Iam trying to write a sequence of tuples to a csv, but the normal File.WriteAllLines is overloaded by a sequence of tuples.
因此,我试图将元组展平为一系列字符串.
I have tried therefore to flatten my tuples into a sequence of strings.
这是我的代码:-
open System;;
open Microsoft.FSharp.Reflection;;
let tupleToString (t: string * float) =
if FSharpType.IsTuple(t.GetType())
then String.Format("{0},{1}", fst t, snd t)
else "";;
let testTuple = ("monkey", 15.168);;
tupleToString(testTuple);;
let testSeqTuple = [("monkey", 15.168); ("donkey", 12.980)];;
let allIsStrings (t:seq<string * float>) = Seq.collect tupleToString t;;
allIsStrings(testSeqTuple);;
当我仅在一个元组上使用"tupleToString"时,结果就很好.
When I use "tupleToString" on just one tuple the results are just fine.
但是allIsStrings的Seq.collect部分返回按字符分解的元组.
However the Seq.collect part of allIsStrings returns the tuples broken down by characters.
我也尝试过Seq.choose和Seq.fold,但是它们只会引发错误.
I have also tried Seq.choose and Seq.fold, but these simply throw errors.
任何人都可以建议我应该使用序列模块中的什么功能-或建议可以在元组上工作的File.WriteAllLines的替代方案吗?
Can anyone advise as to what function from the sequence module I should be using - or advise on an alternative to File.WriteAllLines that would work on a tuple?
推荐答案
您需要使用Seq.map
将列表的所有元素转换为string
,然后使用Array.ofSeq
来获取可以传递给WriteAllLines
:
You need to use Seq.map
to convert all elements of a list to string
and then Array.ofSeq
to get an array which you can pass to WriteAllLines
:
let allIsStrings (t:seq<string * float>) =
t |> Seq.map tupleToString
|> Array.ofSeq
此外,在您的tupleToString
函数中,您无需使用反射来检查参数是否为元组.它始终是一个元组,因为这由类型系统保证.所以你可以这样写:
Also, in your tupleToString
function, you do not need to use reflection to check that the argument is a tuple. It will always be a tuple, because this is guaranteed by the type system. So you can just write:
let tupleToString (t: string * float) =
String.Format("{0},{1}", fst t, snd t)
如果您想对具有任意数量参数的元组使用此功能,您可以 使用反射(但这是更高级的主题).以下获取元组的元素,将它们全部转换为字符串,然后使用逗号将它们连接起来:
You could use reflection if you wanted to make this work for tuples with arbitrary number of parameters (but that is a more advanced topic). The following gets elements of the tuple, converts them all to string and then concatenates them using a comma:
let tupleToString t =
if FSharpType.IsTuple(t.GetType()) then
FSharpValue.GetTupleFields(t)
|> Array.map string
|> String.concat ", "
else failwith "not a tuple!"
// This works with tuples that have any number of elements
tupleToString (1,2,"hi")
tupleToString (1.14,2.24)
// But you can also call it with non-tuple and it fails
tupleToString (new System.Random())
这篇关于将元组序列写入CSV文件F#的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!