I have a C# WebAPI application that uses an F# library.
The F# library has a value:
let mutable CurrentCustomer:Customer option = None
I also have:
let Customers:Map<string,Customer> option = None
Both Customers and Customer are "global variables". On start-up the C# application loads a collection of customers into this global variable Customers. Then I have a customersController that has a Post, which calls an F# function setCurrentCustomer that sets the global variable CurrentCustomer from the collection stored in Customers:
// Post in customersController:
public HttpResponseMessage Post(string identifier)
{
var _customer = FSharpLibrary.setCurrentCustomer(identifier);
// code
}
// setCurrentCustomer function:
let mutable CurrentCustomer:Customer option = None
let setCurrentCustomer() =
CurrentCustomer <- customer |> Some
CurrentCustomer
Is there any way to avoid changing state by changing CurrentCustomer?
I know I could create a function that takes a CurrentCustomer object and returns a new CurrentCustomer object, but how will the customersController know what is the current customer set to?
Is there any way of avoiding having this global mutable variable Customer?
Is there any way to avoid changing state by changing CurrentCustomer?
Yes, there are many ways to do that, but most will involve changing the design of your FSharpLibrary so that it doesn't rely on mutable state.
As a completely general answer, you could apply the State Monad, but something less involved is often sufficient. Exactly what that would be, however, is impossible to answer without knowing what you are attempting to accomplish.
how will the customersController know what is the current customer set to?
It already knows, because it's setting the current customer to the identifier argument from the Post method. That value is in scope throughout the entire method.
The question is why your FSharpLibrary has mutable state? Can't you instead implement it with pure functions?
Related
F# has a rather nice syntax for events, which can be subscribed to as observables without any custom code for that purpose. I am creating an event that publishes updates to a member variable. I intend to subscribe to this event as an observable, but I want the existing value (which I know exists) to be pushed on subscription. Is this possible and simple to do with the event syntax, or do I need to create a proper observable using e.g. BehaviorSubject?
This depends a lot on how you plan to use it.
When you convert from an event to an observable, the EventArgs are mapped through as the observable's type. With a "standard" event, this won't have a value (EventArgs doesn't carry any information).
However, you can easily use a custom event type, or event violate normal .NET guidelines for events and use the value itself:
let evt = Event<int>()
let obs = evt.Publish :> IObservable<_>
obs |> Observable.add (fun v -> printfn "New value: %d" v)
evt.Trigger 3
evt.Trigger 4
That being said, depending on your use case, you may want to look at Gjallarhorn. This library was specifically designed for tracking changes to mutable values and signaling nicely. It's built around the concept of a "signal", which is an observable that contains a current value. This makes the above concept first class - you can pass something (a signal) that can directly be used as an IObservable whenever needed, but also can always be used to get the underlying, current value. In practice, this dramatically simplifies many use cases.
What's the preferred way of getting a value in swift?
Using a read-only variable
var getString: String? {
return "Value"
}
or using a function?
func getString() -> String? {
return "Value"
}
Also, is there a performance difference between the two?
First, neither of these would be appropriate names. They should not begin with get. (There are historical Cocoa meanings for a get prefix that you don't mean, and so even if you mean "go out to the internet and retrieve this information" you'd want to use something like fetch, but certainly not in the case you've given.)
These issues are addressed in various sections of the Swift API Design Guidelines. First, a property is a property, whether it is stored or computed. So there is no difference in design between:
let someProperty: String?
and
var someProperty: String? { return "string" }
You should not change the naming just because it's computed. We can then see in the guidelines:
The names of other types, properties, variables, and constants should read as nouns.
Furthermore, as discussed in The Swift Programming Language:
Properties associate values with a particular class, structure, or enumeration. Stored properties store constant and variable values as part of an instance, whereas computed properties calculate (rather than store) a value.
So if this is best thought of as a value associated with the type (one of its "attributes"), then it should be a property (computed or stored). If it is something that is not really "associated" with the type (something that the caller expects this type to retrieve from elsewhere for instance), then it should be a method. Again from the Design Guidelines:
Document the complexity of any computed property that is not O(1). People often assume that property access involves no significant computation, because they have stored properties as a mental model. Be sure to alert them when that assumption may be violated.
If "stored properties as a mental model" doesn't match what you mean to express, then it probably shouldn't be a property in the first place (and you need to document the discrepancies if you make it a property anyway). So, for instance, accessing a property should generally have no visible side effects. And if you read from a property immediately after writing to it, you should get back the value you wrote (again, as a general mental model without getting into the weeds of multi-threaded programming).
If you use a method, it can often result in a different appropriate name. See the "Strive for Fluent Usage" section of the Design Guidelines for more on that. There are several rules for selecting good method names. As a good example of when to use properties vs methods, consider the x.makeIterator(), i.successor() and x.sorted() examples and think about why these are methods and why they're named as they are. This is not to say there is exactly one answer in all cases, but the Design Guidelines will give you examples of what the Swift team intends.
With no discernible difference in performance, make the choice for readability:
When an attribute behaves like a variable, use a property. Your example falls into this category.
When reading an attribute changes object state, use a function. This includes
Attributes that behave like a factory, i.e. returns new objects when you access them
Attributes that produce new values, such as random number generators
Peripheral readers
Input iterators
Of course, if the attribute is computed based on one or more argument, you have no other choice but to use a function.
Just as a note: If you want to use both getters and setters in Swift you can do as follows:
var myString: String {
get {
return "My string"
}
set {
self.myPrivateString = newValue
}
}
This way you can access your value as if it was a regular variable, but you can do some "under-the-hood magic" in your getters and setters
I'm new to Dart, so maybe I'm missing something here:
This works:
In my main(), I have this:
var a = _someFunction;
var b = _someFunction;
print("${a == b}"); // true. correct!
Where _someFunction is another top-level function.
This does NOT work: (at least not how I'm expecting it to)
Given this class...
class Dummy {
void start() {
var a = _onEvent;
var b = _onEvent;
print(a == b); // false. ???????
}
void _onEvent() {
}
}
Instantiating it from main() and calling its start() method results in false. Apparently a new instance of some function or closure object is created and returned whenever my code obtains a reference to _onEvent.
Is this intentional behaviour?
I would expect that obtaining multiple references to the same method of the same instance returns the same object each time. Perhaps this is intended for some reason. If so; what reason? Or is this a bug/oversight/limitation of VM perhaps?
Thanks for any insights!
Currently, the behaviour seems to be intentional, but the following defect is open since May 2012: https://code.google.com/p/dart/issues/detail?id=144
If I were to guess, I'd say that setting "var a = _onEvent;" creates a bound method, which is some sort of object that contains both the function as well as this. You are asking for bound methods to be canonicalized. However, that would require the team to create a map of them, which could lead to worries about memory leaks.
I think they made "var a = _someFunction;" work early on because they needed static functions to be constants so that they could be assigned to consts. This was so that they could write things like:
const logger = someStaticLoggingFunction;
This was in the days before statics were lazily evaluated.
In any case, I would say that comparing closures for equality is a edge case for most languages. Take all of the above with a grain of salt. It's just my best guess based on my knowledge of the system. As far as I can tell, the language spec doesn't say anything about this.
Actually, now that I've read (https://code.google.com/p/dart/issues/detail?id=144), the discussion is actually pretty good. What I wrote above roughly matches it.
How can I create a binding for a globally scoped singleton object whose instance expires after a certain amount of time? Once the object has expired I'd like Ninject to serve up a new instance until that instance expires, etc...
Pseudo binding to get the idea across:
Bind<Foo>().ToSelf()
.InSingletonScope()
.WithExpiration(someTimeSpan);
I'm not looking for that exact syntax, but rather a way to end up with the desired result. In essence it would be like using Ninject as a sliding app cache.
Update
The methodology that Ian suggested was correct. I just had to tweak it a little bit because using a DateTime as the context key didn't work for some reason. Here's what I ended up with:
var someTimeInFuture = DateTime.Now.AddSeconds(10);
var fooScopeObject = new object();
Func<IContext, object> scopeCall = ctx =>
{
if (someTimeInFuture < DateTime.Now)
{
someTimeInFuture = DateTime.Now.AddSeconds(10);
fooScopeObject = new object();
}
return fooScopeObject;
};
Kernel.Bind<Foo>()
.ToSelf()
.InScope(scopeCall);
You are essentially defining a timed scope. You can bind using a custom scope function and return null after a period of time.
var someTimeInFuture = DateTime.Now.AddMinutes(5);
Func<IContext,object> scopeCall = ctx => DateTime.Now > someTimeInFuture ? null : someTimeInFuture;
Kernel.Bind<Foo>().ToSelf().InScope(scopeCall);
I am not able to test this right now, but that may work.
You can use InScope(Func scope). As the documentation states:
Indicates that instances activated via the binding should be re-used as long as the object
returned by the provided callback remains alive (that is, has not been garbage collected).
You would need to implement your own custom scope which handles your scenario. A good example how to implement your own scoping is the named scope extension from
https://github.com/ninject/ninject.extensions.namedscope
Is there a clever way to record changes made to an object in F#?
I have been researching F# as a way to build an object model that replicates itself over the network. One task I need to solve is how to detect changes made to objects so I can send only changes to clients
Note: I am looking for answers other than "implement INotifyPropertyChanged" or "do something that can easily be done in C#". If that is the only way to solve the problem in F# then F# is not the tool im looking for.
Why F#? Because I am not satisfied with the ways this state observer pattern is implemented in C#. Hence I am investigating if there is some elegant way to implement it in a dynamic language, starting with F#.
Instead of detecting and notifying changes as they happen, you could make your classes immutable (for example by using the standard immutable types like records and unions, or by making the object contain only immutable things). Then you could write a function that "diffs" two instances of a class, and have some agent that looks for changes on a schedule or based on some trigger and sends the diffs to the other end.
Because the data would be immutable, the agent would only need to retain a pointer to the version it last sent. The diffing function itself could either be written by hand for each class, which would allow for an efficient implementation that takes the properties of the data into account, or you could write a generic one using reflection.
An example of INotifyPropertyChanged use in F#.
type DemoCustomer() =
let mutable someValue = 0
let propertyChanged = Event<_, _>()
member this.MyProperty
with get() = someValue
and set(x) =
someValue <- x
propertyChanged.Trigger(this, PropertyChangedEventArgs("MyProperty"))
interface INotifyPropertyChanged with
[<CLIEvent>]
member this.PropertyChanged = propertyChanged.Publish
How about using the INotifyPropertyChanged interface? and raise events that cause the data to be replicated when it is changed?
I'd use a proxy library: Castle DynamicProxy, LinFu, Spring.NET, etc.
Using a proxy library you can easily implement INotifyPropertyChanged in a transparent, non-invasive way.
Can you use reflection to walk the object fields and see what changed? If they contain immutable F# data then equality checks will pick up the changes. You can then send the diffs relative to the last sent object.