In C #, I have the following code:
public class SomeKindaWorker { public double Work(Strategy strat) { int i = 4;
This is a piece of code that can do some work using the provided strategy object to populate implementation parts. Note: in general, strategy objects do not contain state; they simply provide polymorphic implementation of individual steps.
The strategy class is as follows:
public abstract class Strategy { public abstract string Step1(int i); public abstract double Step2(string s); } public class StrategyA : Strategy { public override string Step1(int i) { return "whatever"; } public override double Step2(string s) { return 0.0; } } public class StrategyB : Strategy { public override string Step1(int i) { return "something else"; } public override double Step2(string s) { return 4.5; } }
Observation . The same effect can be achieved in C # with lambdas (and generally get rid of the strategy object), but the good thing about this implementation is that expandable classes have their own Step1 and Step2 together.
Question : What is the idiomatic implementation of this idea in F #?
Thoughts:
I could introduce individual step functions into the Work function, similar to the idea of observation.
I could also create a type that collects two functions and passes the value of that type with:
type Strategy = { Step1: int -> string; Step2: string -> double } let strategyA = { Step1 = (fun i -> "whatever"); Step2 = fun s -> 0.0 } let strategyB = { Step1 = (fun i -> "something else"); Step2 = fun s -> 4.5 }
This seems like the closest match I am trying to achieve: it keeps the implementation steps close together so that they can be seen as a group. But is this idea (creating a type containing only the values of functions) idiomatic in the functional paradigm? Any other thoughts?
source share