Observable from Sequence in F# - f#

Is there a way to creating an observable from a sequence in F#?
The required behaviour is that an observer subscribing to the resulting observable receives all the values of the sequence one at a time.
Edit: The question can be framed as: Is there an equivalent to Rx.Observable.FromArray([1,2,3]) as shown here in F#?
Edit 2: Thanks everyone. It took me some time to find the answer, only to find that desco has answered already. For the sake of completeness, here is how it works:
//Using the Reactive Framework.
//References to System.CoreEx.dll and System.Reactive.dll are needed.
open System.Linq
let observable = Observable.ToObservable [1..10]
let odds = observable |> Observable.filter (fun i -> i%2=1)
let disp = odds.Subscribe (fun i -> printfn "%d" i)
disp.Dispose ()

Just in case you wanted to avoid the additional dependency, it is actually quite easy to implement the behavior using F# events and Observable.guard function that I already used in another answer here at StackOverflow.
Here is the implementation together with a brief example:
module Observable =
let ofSeq s =
let evt = new Event<_>()
evt.Publish |> Observable.guard (fun o ->
for n in s do evt.Trigger(n))
[ 1 .. 10 ] |> Observable.ofSeq
|> Observable.filter (fun n -> n%2 = 0)
|> Observable.add (printfn "%d")
And for completeness, the implementation of Observable.guard looks like this:
/// Creates an observable that calls the specified function after someone
/// subscribes to it (useful for waiting using 'let!' when we need to start
/// operation after 'let!' attaches handler)
let guard f (e:IObservable<'Args>) =
{ new IObservable<'Args> with
member x.Subscribe(observer) =
let rm = e.Subscribe(observer) in f(); rm }

Is System.Reactive.Linq.Observable.ToObservable(this IEnumerable source) located in System.Reactive.dll the thing your wanted?

Yoou can try Reactive Extensions. Please refer to the following blog entry which might help you a lot.
http://www.navision-blog.de/2009/10/20/iobservableiobserver-using-the-reactive-framework-with-f/

Related

F# hidden mutation

Anyone have a decent example, preferably practical/useful, they could post demonstrating the concept?
I came across this term somewhere that I’m unable to find, probably it has to do something with a function returning a function while enclosing on some mutable variable. So there’s no visible mutation.
Probably Haskell community has originated the idea where mutation happens in another area not visible to the scope. I maybe vague here so seeking help to understand more.
It's a good idea to hide mutation, so the consumers of the API won't inadvartently change something unexpectedly. This just means that you have to encapsulate your mutable data/state. This can be done via objects (yes, objects), but what you are referring to in your question can be done with a closure, the canonical example is a counter:
let countUp =
let mutable count = 0
(fun () -> count <- count + 1
count)
countUp() // 1
countUp() // 2
countUp() // 3
You cannot access the mutable count variable directly.
Another example would be using mutable state within a function so that you cannot observe it, and the function is, for all intents and purposes, referentially transparent. Take for example the following function that reverses a string not character-wise, but rather by taking individual text elements (which, depending on language, can be more than one character):
let reverseStringU s =
if Core.string.IsNullOrEmpty s then s else
let rec iter acc (ee : System.Globalization.TextElementEnumerator) =
if not <| ee.MoveNext () then acc else
let e = ee.GetTextElement ()
iter (e :: acc) ee
let inline append x s = (^s : (member Append : ^x -> ^s) (s, x))
let sb = System.Text.StringBuilder s.Length
System.Globalization.StringInfo.GetTextElementEnumerator s
|> iter []
|> List.fold (fun a e -> append e a) sb
|> string
It uses a StringBuilder internally but you cannot observe this externally.

Cannot get model based test working

As an exercise I wanted to implement a 2-3 finger tree. That should be the perfect opportunity to try out FsCheck's model-based testing. I decided to try the newer experimental version.
So far I only coded one command for the test machine because I already fail at making that work—one the other hand it keeps the post short. The full code is available on GitHub.
open CmdQ
open Fuchu
open FsCheck
open FsCheck.Experimental
type TestType = uint16
type ModelType = ResizeArray<TestType>
type SutType = FingerTree<TestType>
let spec =
let prepend (what:TestType) =
{ new Operation<SutType, ModelType>() with
override __.Run model =
// Also tried returning the same instance.
let copy = model |> ResizeArray
copy.Insert(0, what)
copy
override __.Check(sut, model) =
let sutList = sut |> Finger.toList
let newSut = sut |> Finger.prepend what
let newSutList = newSut |> Finger.toList
let modelList = model |> Seq.toList
let areEqual = newSutList = modelList
areEqual |# sprintf "prepend: model = %A, actual = %A (incoming was %A)" modelList newSutList sutList
override __.ToString() = sprintf "prepend %A" what
}
let create (initial:ModelType) =
{ new Setup<SutType, ModelType>() with
override __.Actual () = initial |> Finger.ofSeq
override __.Model () = initial //|> ResizeArray // Also tried this.
}
let rndNum () : Gen<TestType> = Arb.from<uint16> |> Arb.toGen
{ new Machine<SutType, ModelType>() with
override __.Setup =
rndNum()
|> Gen.listOf
|> Gen.map ResizeArray
|> Gen.map create
|> Arb.fromGen
override __.Next _ = gen {
let! cmd = Gen.elements [prepend]
let! num = rndNum()
return cmd num
}
}
[<Tests>]
let test =
[spec]
|> List.map (StateMachine.toProperty >> testProperty "Finger tree")
|> testList "Model tests"
What I understand is this: Operation<_>.Run is run twice to build up a ResizeArray from one with a single element. Then Operation<_>.Check is run twice with the same numbers to insert into a single element FingerTree<_>.
The first of the two passes. Single-element tree incoming, adding makes it a (correct) two-element tree which compares well against the model after the first command.
The second command is always the one failing. Check is called with the bigger ResizeList (now 3 elements) but the same single-element Tree as in the first command. Adding one more element of course does not get it to size 3 and the test fails.
I would have expected that I need to return the updated model from Check for the commands to come. But you need to return a Property so that's not possible.
Did I completely misunderstand how to approach this? How should a working model-based test be written?
The model-based testing assumes that the "system under test" is modified as a side-effect when Check is called on a particular operation, and initialized for that test run when Setup.Actual() is called. It is intended for dealing with systems that are mutable - like a mutable object - and that style while somewhat bewildering here works out quite nicely with such systems.
Since your finger tree type is immutable, my advice would be to redefine SutType to:
type SutType = Ref<FingerTree<TestType>>
and modify the rest accordingly.

F# Async.Map not found

I have source from http://sourceforge.net/p/onvifdm/code/HEAD/tree/
When I try to build this solution, I get the following issue in the onvif.utils project.
use! response = request.AsyncGetResponse() |> Async.Map(fun x-> x:?>HttpWebResponse)
Error: Method or object constructor 'Map' not found
D:\Working\onvifdm\onvifdm-code-96-trunk\onvif\onvif.utils\OdmSession.fs
Here's a function that extends Async, taken from a useful source on understanding map.
module Async =
let map f op = async {
let! x = op
let value = f x
return value
}
Which has a type signature ('a -> 'b) -> Async<'a> -> Async<'b>
For example -
let onInts = async { return 1 }
... is an async<int>, and ...
let onStrings = Async.map (fun x -> x.ToString()) onInts
... produces an Async<string>.
You can use following code as a replacement:
let! webResponse = request.AsyncGetResponse()
use response = webResponse:?>HttpWebResponse
Also you can write your own extension to Async type - here is an example how it can be done. All you need is to implement high order function for the code above.
For those still looking for an answer to this, the problem is that Async is referencing the wrong class. Change it to Microsoft.FSharp.Control.Async and the problem should be resolved.
if this is still an open question, let me suggest using FsToolkit.ErrorHandling:
[https://www.nuget.org/packages/FsToolkit.ErrorHandling]
It contains an Async.map implementation and a lot of useful features to deal with Result.
As an alternative I think this should work:
use! response = request.AsyncGetResponse() |> async.Bind (fun x-> x:?>HttpWebResponse |> async.Return)

How do I use an async workflow in a Seq.pick in F#

I am new to functional programming in general and started learning F# recently. I wanted to use an async workflow returning Async<'U option> to pick an item in a Sequence. I find a nice Seq.pick function, but I am not sure how I could use that with an async workflow.
If that is not possible, is there another alternative to using an imperative style program to pick the item from the list. The following is a modified variation of my program. Any feedback is highly appreciated.
let run = async {
while not stopped do
use! resource = acquireResourceLockAsync
let! items = fetchItemsAsync 5
let! item = Seq.pick returnIfLocked items
let! status = performTaskAsync item
do! updateStatusAsync status
do! Async.Sleep 1000
}
Thanks in anticipation.
EDIT: Updated my question based on the answer by jpalmer. I noticed both Seq.filter and Seq.pick earlier and decided that Seq.pick will meet my need better, as I need the first item that I am able to lock. However, I forgot to change the return value of my function - instead of returning true, it should return Some(item). Now with that update, is there an elegant way to approach this without 1) blocking a thread to convert Async<'U option> to 'U and 2) resorting to an imperative style looping?
I am unclear exactly what you are trying to do. If you want to convert from Async<'T> to 'T non-blocking, then you want to use let! in an async workflow. So the seq-like logic probably needs to be written as its own loop, as suggested below. If that doesn't help, then perhaps share more code, especially the intended types of items/item/returnIfLocked, as I'm unclear what's async in your example.
let asyncPick f (s:seq<_>) =
async {
use e = s.GetEnumerator()
let r = ref None
while Option.isNone(!r) && e.MoveNext() do
let! x = f e.Current
r := x
match !r with
| Some z -> return z
| None -> return failwith "no matching item found"
}
let chooser ax =
async {
let! x = ax
if x%3 = 0 then
return Some x
else
return None
}
let s = seq { for i in 1..10 do yield async { return i } }
let main() =
async {
let! firstChosen = s |> asyncPick chooser
return firstChosen
}
|> Async.RunSynchronously
|> printfn "%d"
main()
It is important to look at the signature of the function you are using,
Seq.pick expects a function which returns option<'t>, you want to use Seq.Filter which takes a function which returns a bool.
You will still have another problem though in that you have Async<bool> - you will need to convert that to a normal bool, but you could do this inside your 'Seq.Filter' function

Applying Seq.map using 2 sequences to a method which takes 2 parameters

I'm writing a quick DB perf test, and chose F# so I can get more practice.
I've created a method, measureSelectTimes, which has the signature Guid list * Guid list -> IDbCommand -> TimeSpan * TimeSpan.
Then, I call it:
let runTests () =
let sqlCeConn : IDbConnection = initSqlCe() :> IDbConnection
let sqlServerConn : IDbConnection = initSqlServer() :> IDbConnection
let dbsToTest = [ sqlCeConn; sqlServerConn ]
let cmds : seq<IDbCommand> = dbsToTest |> Seq.map initSchema
let ids : seq<Guid list * Guid list> = cmds |> Seq.map loadData
let input = Seq.zip ids cmds
let results = input |> Seq.map (fun i -> measureSelectTimes (fst i) (snd i))
// ...
I've annotated explicitly with types to clarify.
What I can't figure out is how to call measureSelectTimes without the lambda. I'd like to partially apply the ids to it like this: ids |> Seq.map measureSelectTimes but then I don't know what to do with the resulting partially applied functions to then map onto the cmds. What's the syntax for this?
You can use Seq.map2:
Seq.map2 measureSelectTimes ids cmds
Or
(ids, cmds) ||> Seq.map2 measureSelectTimes
Your measureSelectTimes function takes two arguments as separate arguments, but you instead need a function that takes them as a tuple. One option is to just change the function to take a tuple (if it is logical for the arguments to be tupled).
Alternative, you can write a cobinator that turns a function taking two arguments into a function taking tuple. This is usually called uncurry and it exists in some functional language:
let uncurry f (a, b) = f a b
Then you can write:
input |> Seq.map (uncurry measureSelectTimes)
This looks okay for a simple use like this, but I think that using combinators too much in F# is not a good idea as it makes code difficult to read for less experienced functional programmers. I would probably write something like this (because I find that more readable):
[ for (time1, time2) in input -> measureSelectTimes time1 time2 ]
One approach is to change the signature of measureSelectTimes to
(Guid list * Guid list) * IDbCommand -> TimeSpan * TimeSpan
Then you can change the map call to
let results = input |> Seq.map measureSelectTimes
// or
let results = Seq.map measureSelectTimes input

Resources