Reputation: 1156
I would like to use some object-oriented code in a more functional way. My current approach has been the following:
let addControl (child: Control) (parent: Control) =
parent.Controls.Add child
parent
let setDock dock (control : Control) =
control.Dock <- dock
control
form |> addControl button
button |> setDock DockStyle.Fill
Is there a simpler way I can define these functions?
If I take the JS approach I could define something like the following:
const fixMethod = name => value => parent => (parent[name](value), parent)
const resumeLayout = fixMethod("ResumeLayout")
resumeLayout(true)(form)
const fixAssign = name => value => parent => ({...parent, [name]: value})
const setDock = fixAssign("Dock")
setDock(DockStyle.Fill)(button)
Upvotes: 0
Views: 120
Reputation: 243051
There are various tricks you could do in F#, but none of those will make your code much nicer - I would say that most tricks you can do will actually only make it more complex and unidiomatic.
There is nothing wrong with writing some imperative-looking code if that's what the underlying libraries look like. F# does have a few features that make this easier - you can, for example, specify mutable properties directly when calling a constructor, so you can set Dock
as follows:
let button = new Button(Dock = DockStyle.Fill)
let form = new Form()
form.Controls.Add(button)
Upvotes: 1