porting a dequeue - add loop from C# to F# - c#

I am trying to port this simple loop:
var messages = new List<string>();
while (_MessageQueue.TryDequeue(out var message))
messages.Add(message);
where the message queue is concurrent. It is used in a module that enqueues messages from several threads and they are then processed by a single thread.
Is there an idiomatic F# way to do the dequeue / add loop?

F# has a couple of ways of doing concurrency including a nice support for agent-based programming, so it is quite possible that the idiomatic F# version of what you are doing would not actually use conrrent queues, but would be instead based on agents or some other architecture.
However, to answer your specific question about looping - the C# version is quite terse thanks to the clever use of while and out var. In F#, you can call TryDequeue as a method that returns bool together with the value (so we can avoid mutation). I would use that, together with a recursive sequence expression:
let mq = System.Collections.Concurrent.ConcurrentQueue<int>()
let rec readAll () = seq {
let succ, msg = mq.TryDequeue()
if succ then
yield msg
yield! readAll() }
let messages = readAll() |> List.ofSeq
The readAll function defines a sequence (IEnumerable) that calls TryDequeue and if the operation succeeds, it adds the message to the result using yield msg and then recursively tries to read more messages by using yield!.

Here's a straight conversion:
open System.Collections.Concurrent
let _MessageQueue = ConcurrentQueue<string>()
let messages = ResizeArray<string>()
let mutable continueLooping = true
while continueLooping do
let success, message = _MessageQueue.TryDequeue()
if success then messages.Add(message)
continueLooping <- success

While this question already has an accepted answer, I wanted to contribute an alternative implementation using the library function Seq.unfold:
let getAllMessages (mq : _ ConcurrentQueue) =
mq |> Seq.unfold (fun q ->
match q.TryDequeue () with
| true, m -> Some (m, q)
| _ -> None)
let messages = getAllMessages _MessageQueue |> Seq.toList
Not sure if internally it is as complex as (or even more than) Tomas's solution but I find it is short, understandable, and elegant.

I'm providing a couple additional design options for giggles. The common parts:
open System.Collections.Concurrent
type Message = { I: int }
let queue = ConcurrentQueue<Message>()
drain1 invokes queue.GetEnumerator(), which has the condition that it's returning a snapshot at the time of the initial request. The snapshot is, substantially, the same race condition in the C# version.
let drain1 () = queue |> Seq.toList
drain2 returns an array instead, again a snapshot at the time of the initial request. In case you have the luxury of changing the return type.
let drain2 () = queue.ToArray()
This is an example of the idiomatic return from TryQueue, it avoids an 'out' arg, therefore it's not a mutable value as C# does/did it.
let example () =
let (success, message) = queue.TryDequeue()
() // ...
Finally, a recursively built, self-terminating sequence.
let drain3 () =
let rec drain () = seq {
let success, message = queue.TryDequeue()
if success then
yield message
yield! drain()
}
drain() |> Seq.toList
(Standard Internet warranty applies.)

Riffing on #Scott Hutchinson's answer
I'd define an efficient, straightforward helper that encapsulates the mutation and looping :-
[<AutoOpen>]
module ConcurrentQueueExtensions =
type System.Collections.Concurrent.ConcurrentQueue<'T> with
member this.Drain() =
let buffer = ResizeArray(this.Count)
let mutable more = true
while more do
match this.TryDequeue() with
| true, req -> buffer.Add req
| false, _ -> more <- false
buffer.ToArray()
or even leave that generic helper in C#:
class ConcurrentQueueExtensions
{
public static T[] Drain<T>(this System.Collections.Concurrent.ConcurrentQueue<T> that)
{
var buffer = new List<T>(that.Count);
while (that.TryDequeue(out var req))
buffer.Add(req);
return buffer.ToArray();
}
}
and then apply it with no mixing of paradigms:
let messages = queue.Drain()

Related

Is there a way to switch on partial strings in c#?

I have a list of different types of images I need to store in a database, they all have a type description such as Indoor or GardenSummer and things like that, but there are a lot of the descriptions that contain repeated words, like GardenSummer and AreaSummer1KM for example both contain "Summer", so is there a way for me to do something like this in c#:
open System
let strs = ["Kitchen"; "GardenSummer"; "GardenWinter"; "AreaSummer1KM"; "PoolIndoors"; "LivingRoom"; "BathRoom"]
let switch (x: string) = match x with
| a when a.Contains "Summer" -> Some "Summer" // here
| b when b.Contains "Winter" -> Some "Winter" // here
| "Exterior" | "ParkFacilities" -> Some "Outdoors"
| "Kitchen" | "Landing" -> Some "Indoors"
| c when c.Contains "Room" -> Some "Indoors" // and here
| _ -> None
let sorted = List.map switch strs
// part from here and down was just added to print the contents, and isn't a part of the issue
let printOption = function
| Some v -> v.ToString () |> Console.WriteLine
| None -> "No Match" |> Console.WriteLine
List.iter printOption sorted
is there a way for me to switch on str.Contains(str2) without making a bunch of else ifs?
The short answer is no.
The slightly longer answer is "no, for a good reason". The switch statement is actually quite a smart statement, that performs better than a chain of if-else if statements in many cases (a good example being the typical switch (MessageType) ...). To do this, however, it requires certain contracts to be held. In the end, it doesn't evaluate every possibility. It performs something similar to a binary search on the possible options.
In the end, your F# code probably does the equivalent of if-else if statements, rather than the equivalent of switch in C#.
Of course, nothing prevents you from creating your own method that would be syntactically similar to F#'s match. Anonymous delegates, generic functions, all those make it rather easy to write such syntax shorteners :)
And of course, there's other options too, like using regular expressions or such. Calling Contains 10 times in a row is going to mean a significant performance penalty if the searched string is long.
Some sample regexes for your data and switches. The common code is as follows:
void Main()
{
var data =
new []
{
"Kitchen", "GardenSummer", "GardenWinter", "AreaSummer1KM",
"PoolIndoors", "LivingRoom", "BathRoom", "Exterior", "ParkFacilities"
};
foreach (var str in data)
{
Matcher(str).Dump();
}
}
Now the thing we're going to change is the Matcher method implementation.
First, to just simplify the whole thing and avoid multiple string matching (comparing strings isn't exactly free):
Regex matcherRegex = new Regex("(Summer)|(Winter)|(^Exterior|ParkFacilities$)",
RegexOptions.Compiled);
string Matcher(string input)
{
var m = matcherRegex.Match(input);
if (m.Groups.Count == 4)
{
if (m.Groups[0].Success) return "Summer";
else if (m.Groups[1].Success) return "Winter";
else if (m.Groups[2].Success) return "Outdoors";
}
return null;
}
So, we still have a if-else chain, but we no longer traverse the strings multiple times. It also allows you to easily specify the conditions you want.
One way to improve this to be more "switchy" is by using LINQ. This is definitely not something you want to do for performance reasons, it's only about aesthetics:
var groupIndex = m.Groups.OfType<Group>()
.Skip(1)
.Select((i, idx) => new { Item = i, Index = idx + 1 })
.Where(i => i.Item.Success)
.Select(i => i.Index)
.FirstOrDefault();
switch (groupIndex)
{
case 0: return null;
case 1: return "Summer";
case 2: return "Winter";
case 3: return "Outdoors";
}
Basically, I get the index of the matched group, and use a switch on that. As I said before, this is probably going to be slower than the first variant, at least due to the LINQ overhead.
You can also use named captures to get the matched groups by name, rather than by index, which is a bit more maintainable. Also, for simple cases, you could use the named group name to avoid the switch altogether:
Regex matcherRegex =
new Regex("(?<Summer>Summer)"
+ "|(?<Winter>Winter)"
+ "|(?<Outdoors>(^Exterior|ParkFacilities$))",
RegexOptions.Compiled | RegexOptions.ExplicitCapture);
string Matcher(string input)
{
return matcherRegex.Match(input)
.Groups
.OfType<Group>()
.Select((i, idx) => new { Item = i, Index = idx })
.Skip(1)
.Where(i => i.Item.Success)
.Select(i => matcherRegex.GroupNameFromNumber(i.Index))
.FirstOrDefault();
}
All of those are just samples, you may want to change those for better edge case or exception handling, and performance, but it shows the ideas.
The last version in particular is handy in that there's nothing preventing you from using this as a common method that handles all the string "switches" that you can explain in regular expressions. Sadly, group names allow a lot of unicode characters, but not whitespaces; it's nothing you couldn't work around, though.
You could even build the pattern matcher automatically, for example by passing Expression<Func<...>> to a helper method, but that's going into complicated territory :)

What is the simplest way to access data of an F# discriminated union type in C#?

I'm trying to understand how well C# and F# can play together. I've taken some code from the F# for Fun & Profit blog which performs basic validation returning a discriminated union type:
type Result<'TSuccess,'TFailure> =
| Success of 'TSuccess
| Failure of 'TFailure
type Request = {name:string; email:string}
let TestValidate input =
if input.name = "" then Failure "Name must not be blank"
else Success input
When trying to consume this in C#; the only way I can find to access the values against Success and Failure (failure is a string, success is the request again) is with big nasty casts (which is a lot of typing, and requires typing actual types that I would expect to be inferred or available in the metadata):
var req = new DannyTest.Request("Danny", "fsfs");
var res = FSharpLib.DannyTest.TestValidate(req);
if (res.IsSuccess)
{
Console.WriteLine("Success");
var result = ((DannyTest.Result<DannyTest.Request, string>.Success)res).Item;
// Result is the Request (as returned for Success)
Console.WriteLine(result.email);
Console.WriteLine(result.name);
}
if (res.IsFailure)
{
Console.WriteLine("Failure");
var result = ((DannyTest.Result<DannyTest.Request, string>.Failure)res).Item;
// Result is a string (as returned for Failure)
Console.WriteLine(result);
}
Is there a better way of doing this? Even if I have to manually cast (with the possibility of a runtime error), I would hope to at least shorten access to the types (DannyTest.Result<DannyTest.Request, string>.Failure). Is there a better way?
Working with discriminated unions is never going to be as straightforward in a language that does not support pattern matching. However, your Result<'TSuccess, 'TFailure> type is simple enough that there should be some nice way to use it from C# (if the type was something more complicated, like an expression tree, then I would probably suggest to use the Visitor pattern).
Others already mentioned a few options - both how to access the values directly and how to define Match method (as described in Mauricio's blog post). My favourite method for simple DUs is to define TryGetXyz methods that follow the same style of Int32.TryParse - this also guarantees that C# developers will be familiar with the pattern. The F# definition looks like this:
open System.Runtime.InteropServices
type Result<'TSuccess,'TFailure> =
| Success of 'TSuccess
| Failure of 'TFailure
type Result<'TSuccess, 'TFailure> with
member x.TryGetSuccess([<Out>] success:byref<'TSuccess>) =
match x with
| Success value -> success <- value; true
| _ -> false
member x.TryGetFailure([<Out>] failure:byref<'TFailure>) =
match x with
| Failure value -> failure <- value; true
| _ -> false
This simply adds extensions TryGetSuccess and TryGetFailure that return true when the value matches the case and return (all) parameters of the discriminated union case via out parameters. The C# use is quite straightforward for anyone who has ever used TryParse:
int succ;
string fail;
if (res.TryGetSuccess(out succ)) {
Console.WriteLine("Success: {0}", succ);
}
else if (res.TryGetFailure(out fail)) {
Console.WriteLine("Failuere: {0}", fail);
}
I think the familiarity of this pattern is the most important benefit. When you use F# and expose its type to C# developers, you should expose them in the most direct way (the C# users should not think that the types defined in F# are non-standard in any way).
Also, this gives you reasonable guarantees (when it is used correctly) that you will only access values that are actually available when the DU matches a specific case.
A really nice way to do this with C# 7.0 is using switch pattern matching, it's allllmost like F# match:
var result = someFSharpClass.SomeFSharpResultReturningMethod()
switch (result)
{
case var checkResult when checkResult.IsOk:
HandleOk(checkResult.ResultValue);
break;
case var checkResult when checkResult.IsError:
HandleError(checkResult.ErrorValue);
break;
}
EDIT: C# 8.0 is around the corner and it is bringing switch expressions, so although I haven't tried it yet I am expecting we will be able to do something like this this:
var returnValue = result switch
{
var checkResult when checkResult.IsOk: => HandleOk(checkResult.ResultValue),
var checkResult when checkResult.IsError => HandleError(checkResult.ErrorValue),
_ => throw new UnknownResultException()
};
See https://blogs.msdn.microsoft.com/dotnet/2018/11/12/building-c-8-0/ for more info.
How about this? It's inspired by #Mauricio Scheffer's comment above and the CSharpCompat code in FSharpx.
C#:
MyUnion u = CallIntoFSharpCode();
string s = u.Match(
ifFoo: () => "Foo!",
ifBar: (b) => $"Bar {b}!");
F#:
type MyUnion =
| Foo
| Bar of int
with
member x.Match (ifFoo: System.Func<_>, ifBar: System.Func<_,_>) =
match x with
| Foo -> ifFoo.Invoke()
| Bar b -> ifBar.Invoke(b)
What I like best about this is that it removes the possibility of a runtime error. You no longer have a bogus default case to code, and when the F# type changes (e.g. adding a case) the C# code will fail to compile.
You can use C# type aliasing to simplify referencing the DU Types in a C# File.
using DanyTestResult = DannyTest.Result<DannyTest.Request, string>;
Since C# 8.0 and later have Structural pattern matching, it's easy to do the following:
switch (res) {
case DanyTestResult.Success {Item: var req}:
Console.WriteLine(req.email);
Console.WriteLine(req.name);
break;
case DanyTestResult.Failure {Item: var msg}:
Console.WriteLine("Failure");
Console.WriteLine(msg);
break;
}
This strategy is the simplest as it works with reference type F# DU without modification.
The syntax C# syntax could be reduced more if F# added a Deconstruct method to the codegen for interop. DanyTestResult.Success(var req)
If your F# DU is a struct style, you just need to pattern match on the Tag property without the type. {Tag:DanyTestResult.Tag.Success, SuccessValue:var req}
Probably, one of the simplest ways to accomplish this is by creating a set of extension methods:
public static Result<Request, string>.Success AsSuccess(this Result<Request, string> res) {
return (Result<Request, string>.Success)res;
}
// And then use it
var successData = res.AsSuccess().Item;
This article contains a good insight. Quote:
The advantage of this approach is 2 fold:
Removes the need to explicitly name types in code and hence gets back the advantages of type inference;
I can now use . on any of the values and let Intellisense help me find the appropriate method to use;
The only downfall here is that changed interface would require refactoring the extension methods.
If there are too many such classes in your project(s), consider using tools like ReSharper as it looks not very difficult to set up a code generation for this.
I had this same issue with the Result type. I created a new type of ResultInterop<'TSuccess, 'TFailure> and a helper method to hydrate the type
type ResultInterop<'TSuccess, 'TFailure> = {
IsSuccess : bool
Success : 'TSuccess
Failure : 'TFailure
}
let toResultInterop result =
match result with
| Success s -> { IsSuccess=true; Success=s; Failure=Unchecked.defaultof<_> }
| Failure f -> { IsSuccess=false; Success=Unchecked.defaultof<_>; Failure=f }
Now I have the choice of piping through toResultInterop at the F# boundary or doing so within the C# code.
At the F# boundary
module MyFSharpModule =
let validate request =
if request.isValid then
Success "Woot"
else
Failure "request not valid"
let handleUpdateRequest request =
request
|> validate
|> toResultInterop
public string Get(Request request)
{
var result = MyFSharpModule.handleUpdateRequest(request);
if (result.IsSuccess)
return result.Success;
else
throw new Exception(result.Failure);
}
After the interop in Csharp
module MyFSharpModule =
let validate request =
if request.isValid then
Success "Woot"
else
Failure "request not valid"
let handleUpdateRequest request = request |> validate
public string Get(Request request)
{
var response = MyFSharpModule.handleUpdateRequest(request);
var result = Interop.toResultInterop(response);
if (result.IsSuccess)
return result.Success;
else
throw new Exception(result.Failure);
}
I'm using the next methods to interop unions from F# library to C# host. This may add some execution time due to reflection usage and need to be checked, probably by unit tests, for handling right generic types for each union case.
On F# side
type Command =
| First of FirstCommand
| Second of SecondCommand * int
module Extentions =
let private getFromUnionObj value =
match value.GetType() with
| x when FSharpType.IsUnion x ->
let (_, objects) = FSharpValue.GetUnionFields(value, x)
objects
| _ -> failwithf "Can't parse union"
let getFromUnion<'r> value =
let x = value |> getFromUnionObj
(x.[0] :?> 'r)
let getFromUnion2<'r1,'r2> value =
let x = value |> getFromUnionObj
(x.[0] :?> 'r1, x.[1] :? 'r2)
On C# side
public static void Handle(Command command)
{
switch (command)
{
case var c when c.IsFirstCommand:
var data = Extentions.getFromUnion<FirstCommand>(change);
// Handler for case
break;
case var c when c.IsSecondCommand:
var data2 = Extentions.getFromUnion2<SecondCommand, int>(change);
// Handler for case
break;
}
}

How can a TPL Dataflow block downstream get data produced by a source?

I'm processing images using TPL Dataflow. I receive a processing request, read an image from a stream, apply several transformations, then write the resulting image to another stream:
Request -> Stream -> Image -> Image ... -> Stream
For that I use the blocks:
BufferBlock<Request>
TransformBlock<Request,Stream>
TransformBlock<Stream,Image>
TransformBlock<Image,Image>
TransformBlock<Image,Image>
...
writerBlock = new ActionBlock<Image>
The problem is the initial Request is what contains some data necessary to create the resulting Stream along with some additional info I need at that point. Do I have to pass the original Request (or some other context object) down the line to the writerBlock across all the other blocks like this:
TransformBlock<Request,Tuple<Request,Stream>>
TransformBlock<Tuple<Request,Stream>,Tuple<Request,Image>>
TransformBlock<Tuple<Request,Image>,Tuple<Request,Image>>
...
(which is ugly), or is there a way to link the first block to the last one (or, generalizing, to the ones that need the additional data)?
Yes, you pretty much need to do what you described, passing the additional data from every block to the next one.
But using a couple of helper methods, you can make this much simpler:
public static IPropagatorBlock<TInput, Tuple<TOutput, TInput>>
CreateExtendedSource<TInput, TOutput>(Func<TInput, TOutput> transform)
{
return new TransformBlock<TInput, Tuple<TOutput, TInput>>(
input => Tuple.Create(transform(input), input));
}
public static IPropagatorBlock<Tuple<TInput, TExtension>, Tuple<TOutput, TExtension>>
CreateExtendedTransform<TInput, TOutput, TExtension>(Func<TInput, TOutput> transform)
{
return new TransformBlock<Tuple<TInput, TExtension>, Tuple<TOutput, TExtension>>(
tuple => Tuple.Create(transform(tuple.Item1), tuple.Item2));
}
The signatures look daunting, but they are actually not that bad.
Also, you might want to add overloads that pass options to the created block, or overloads that take async delegates.
For example, if you wanted to perform some operations on a number using separate blocks, while passing the original number along the way, you could do something like:
var source = new BufferBlock<int>();
var divided = CreateExtendedSource<int, double>(i => i / 2.0);
var formatted = CreateExtendedTransform<double, string, int>(d => d.ToString("0.0"));
var writer = new ActionBlock<Tuple<string, int>>(tuple => Console.WriteLine(tuple));
source.LinkTo(divided);
divided.LinkTo(formatted);
formatted.LinkTo(writer);
for (int i = 0; i < 10; i++)
source.Post(i);
As you can see, your lambdas (except for the last one) deal only with the “current” value (int, double or string, depending on the stage of the pipeline), the “original” value (always int) is passed automatically. At any moment, you can use block created using the normal constructor to access both values (like the final ActionBlock in the example).
(That BufferBlock isn't actually necessary, but I added it to more closely match your design.)
I may be going over my head since I am only starting to play with TPL Dataflow.
But I believe you can accomplish that using a BroadcastBlock as an intermediary between your source and your first target.
BroadcastBlock can offer the message to many targets, so you use it to offer to your target, and also to a JoinBlock, at the end that will merge the result with the original message.
source -> Broadcast ->-----------------------------------------> JoinBlock <source, result>
-> Transformation1 -> Transformation 'n' ->
For example:
var source = new BufferBlock<int>();
var transformation = new TransformBlock<int, int>(i => i * 100);
var broadCast = new BroadcastBlock<int>(null);
source.LinkTo(broadCast);
broadCast.LinkTo(transformation);
var jb = new JoinBlock<int, int>();
broadCast.LinkTo(jb.Target1);
transformation.LinkTo(jb.Target2);
jb.LinkTo(new ActionBlock<Tuple<int, int>>(
c => Console.WriteLine("Source:{0}, Target Result: {1}", c.Item1, c.Item2)));
source.Post(1);
source.Post(2);
source.Complete();
yields...
Source:1, Target Result: 100
Source:2, Target Result: 200
I am just not too sure about how it would behave in an asynchronous environment.

Reactive: Trying to understand how Subject<T> work

Trying to understand how the Subject<T>, ReplaySubject<T> and other work. Here is example:
(Subject is Observable and observer)
public IObservable<int> CreateObservable()
{
Subject<int> subj = new Subject<int>(); // case 1
ReplaySubject<int> subj = new ReplaySubject<int>(); // case 2
Random rnd = new Random();
int maxValue = rnd.Next(20);
Trace.TraceInformation("Max value is: " + maxValue.ToString());
subj.OnNext(-1); // specific value
for(int iCounter = 0; iCounter < maxValue; iCounter++)
{
Trace.TraceInformation("Value: " + iCounter.ToString() + " is about to publish");
subj.OnNext(iCounter);
}
Trace.TraceInformation("Publish complete");
subj.OnComplete();
return subj;
}
public void Main()
{
//
// First subscription
CreateObservable()
.Subscribe(
onNext: (x)=>{
Trace.TraceInformation("X is: " + x.ToString());
});
//
// Second subscribe
CreateObservable()
.Subscribe(
onNext: (x2)=>{
Trace.TraceInformation("X2 is: " + x.ToString());
});
Case 1: The strange situation is - when I use Subject<T> no subscription is made (???) - I never see the "X is: " text - I only see the "Value is: " and "Max value is"... Why does Subject<T> does not push values to subscription ?
Case 2: If I use ReplaySubject<T> - I do see the values in Subscription but I could not apply Defer option to anything. Not to Subject and not to Observable.... So every subscription will receive different values because CreateObservable function is cold observable. Where is Defer ?
Whenever you need to create an observable out of thin air, Observable.Create should be the first thing to think of. Subjects enter the picture in two cases:
You need some kind of "addressable endpoint" to feed data to in order for all subscribers to receive it. Compare this to a .NET event which has both an invocation side (through delegate invocation) and a subscription side (through delegate combine with +- and -= syntax). You'll find in a lot of cases, you can achieve the same effect using Observable.Create.
You need multicasting of messages in a query pipeline, effectively sharing an observable sequence by many forks in your query logic, without triggering multiple subscriptions. (Think of subscribing to your favorite magazine once for your dorm and putting a photo copier right behind the letter box. You still pay one subscription, though all of your friends can read the magazine delivered through OnNext on the letter box.)
Also, in a lot of cases, there's already a built-in primitive in Rx that does exactly what you need. For example, there's From* factory methods to bridge with existing concepts (such as events, tasks, asynchronous methods, enumerable sequence), some of which using a subject under the covers. For the second case of multicasting logic, there's the Publish, Replay, etc. family of operators.
You need to be mindful of when code is executed.
In "Case 1", when you use a Subject<T>, you'll notice that the all of the calls to OnNext & OnCompleted finish before the observable is returned by the CreateObservable method. Since you are using a Subject<T> this means that any subsequent subscription will have missed all of the values so you should expect to get what you got - nothing.
You have to delay the operations on the subject until you have the observer subscribed. To do that using the Create method. Here's how:
public IObservable<int> CreateObservable()
{
return Observable.Create<int>(o =>
{
var subj = new Subject<int>();
var disposable = subj.Subscribe(o);
var rnd = new Random();
var maxValue = rnd.Next(20);
subj.OnNext(-1);
for(int iCounter = 0; iCounter < maxValue; iCounter++)
{
subj.OnNext(iCounter);
}
subj.OnCompleted();
return disposable;
});
}
I've removed all the trace code for succinctness.
So now, for every subscriber, you get a new execution of the code inside the Create method and you would now get the values from the internal Subject<T>.
The use of the Create method is generally the correct way to create observables that you return from methods.
Alternatively you could use a ReplaySubject<T> and avoid the use of the Create method. However this is unattractive for a number of reasons. It forces the computation of the entire sequence at creation time. This give you a cold observable that you could have produced more efficiently without using a replay subject.
Now, as an aside, you should try to avoid using subjects at all. The general rule is that if you're using a subject then you're doing something wrong. The CreateObservable method would be better written as this:
public IObservable<int> CreateObservable()
{
return Observable.Create<int>(o =>
{
var rnd = new Random();
var maxValue = rnd.Next(20);
return Observable.Range(-1, maxValue + 1).Subscribe(o);
});
}
No need for a subject at all.
Let me know if this helps.

What's the use of chords?

Languages such as Nemerle support the idea of chords. I'd like to know what their practical use is.
The construct also seems to exist in the Cω language (as well as Polyphonic C#), at least according to [Wikipedia](http://en.wikipedia.org/wiki/Chord_(concurrency).
The primary usage of chords appears to involve database programming (more specifically, join calculus), which is unsurprising given that it is a concurrency construct. More than that, I'm afraid I don't know.
A chord is used for concurrency. The definition is available here.
The bit you are looking for:
In most languages, including C#, methods in the signature of a class are in bijective correspondence with the code of their implementations -- for each method which is declared, there is a single, distinct definition of what happens when that method is called. In Cω, however, a body may be associated with a set of (synchronous and/or asynchronous) methods. We call such a definition a chord, and a particular method may appear in the header of several chords. The body of a chord can only execute once all the methods in its header have been called. Thus, when a method is called there may be zero, one, or more chords which are enabled:
If no chord is enabled then the method
invocation is queued up. If the method
is asynchronous, then this simply
involves adding the arguments (the
contents of the message) to a queue.
If the method is synchronous, then the
calling thread is blocked. If there
is a single enabled chord, then the
arguments of the calls involved in the
match are de-queued, any blocked
thread involved in the match is
awakened, and the body runs. When a
chord which involves only asynchronous
methods runs, then it does so in a new
thread. If there are several chords
which are enabled then an unspecified
one of them is chosen to run.
Similarly, if there are multiple calls
to a particular method queued up, we
do not specify which call will be
de-queued when there is a match.
Try Nemerle Computation Expressions:
https://code.google.com/p/nemerle/source/browse/nemerle/trunk/snippets/ComputationExpressions/
Some examples:
def upTo (n : int)
{
comp enumerable
{
mutable i = 0;
while (i < n)
{
i ++;
yield i
}
}
}
def manyTimes : IEnumerable [int] =
comp enumerable
{
yieldcomp upTo(2); // 1 2
yield 100; // 100
yieldcomp upTo(3); // 1 2 3
yield 100; // 100
yieldcomp upTo(10); // 1 2 3 .. 10
}
def fn(n)
{
comp async
{
if (n < 20)
returncomp fn(n + 1);
else
return n;
}
}
def f(n1, n2)
{
comp async
{
defcomp n1 = fn(n1);
defcomp n2 = fn(n2);
return $"$n1 $n2";
}
}
private HttpGet(url : string) : Async[string]
{
comp async
{
def req = WebRequest.Create(url);
using (defcomp resp = req.AsyncGetResponse())
using (stream = resp.GetResponseStream())
using (reader = StreamReader(stream))
return reader.ReadToEnd();
}
}
Some more examples here: (Although article in Russian but code in English :) ) http://habrahabr.ru/blogs/programming/108184/

Categories

Resources