How do you pass .net objects values around in F#?
- by Russell
I am currently learning F# and functional programming in general (from a C# background) and I have a question about using .net CLR objects during my processing.
The best way to describe my problem will be to give an example:
let xml = new XmlDocument()
|> fun doc -> doc.Load("report.xml"); doc
let xsl = new XslCompiledTransform()
|> fun doc -> doc.Load("report.xsl"); doc
let transformedXml =
new MemoryStream()
|> fun mem -> xsl.Transform(xml.CreateNavigator(), null, mem); mem
This code transforms an XML document with an XSLT document using .net objects.
Note XslCompiledTransform.Load works on an object, and returns void.
Also the XslCompiledTransform.Transform requires a memorystream object and returns void.
The above strategy used is to add the object at the end (the ; mem) to return a value and make functional programming work.
When we want to do this one after another we have a function on each line with a return value at the end:
let myFunc =
new XmlDocument("doc")
|> fun a -> a.Load("report.xml"); a
|> fun a -> a.AppendChild(new XmlElement("Happy")); a
Is there a more correct way (in terms of functional programming) to handle .net objects and objects that were created in a more OO environment?
The way I returned the value at the end then had inline functions everywhere feels a bit like a hack and not the correct way to do this.
Any help is greatly appreciated!