a_a
a_a

Reputation: 271

How to do **override** in F# module-function structure? (or similar effect)

lets say I have these code--

let plus a b=Seq.init a (fun _->1)|>Seq.fold(+)b
let multiply a b=Seq.init a (fun _->b)|>Seq.fold plus 0
let power a b=Seq.init b (fun _->a)|>Seq.fold multiply 1

How to do it if later I want plus another way--

let shortPlus=(+)

Well, I considered some solutions...

The first is to duplicate whole code, but what if a code is really huge?

let shortPlus=(+)
let multiply a b=Seq.init a (fun _->b)|>Seq.fold shortPlus 0
let power a b=Seq.init b (fun _->a)|>Seq.fold multiply 1

The second is send the plus function as a parameter later customizable--

let customizablePlus f a b=f a b
let customizableMultiply plus a b=customizablePlus plus|>fun plus->Seq.init a (fun _->b)|>Seq.fold plus 0
let customizablePower plus a b=customizableMultiply plus|>fun multiply->Seq.init b (fun _->a)|>Seq.fold multiply 1
let shortPlus=(+)
let power2=customizablePower shortPlus

but -- why should Power take care multiply how to do plus? Why calling power need to tell it how to do plus? It's unnatural!

Well the third guess is-- use the add code file as shortcut ability of VisualStudio-- I will try it a bit later.

Upvotes: 1

Views: 304

Answers (1)

DevNewb
DevNewb

Reputation: 861

You can't override functions like you can methods in C#. But your power function does not depend on plus in the first version, so you don't need to pass it, it just needs multiply function.

let plus1 = (+)
let plus2 a b = plus1 a b |> (+) 1
let customizableMultiply plus a b = Seq.init a (fun _-> b)|>Seq.fold plus 0
let customizablePower multiply a b= Seq.init b (fun _->a)|>Seq.fold multiply 1
let mult1 = customizableMultiply plus1
let mult2 = customizableMultiply plus2
let power1=customizablePower mult1 2 3 //=8
let power2=customizablePower mult2 2 3 //=27

Upvotes: 2

Related Questions