Where is untyped_to_typed method? - f#

I'm learning to use F# to build WPF applications. I using this as reference. I'm stuck with this one example where the author is trying to
IEnumerable.untyped_to_typed
Its giving me a compile error. Is it being renamed or am I missing something?

Looks like that page is referencing previous versions of the Seq and IEnumerable modules.
Use Seq.cast instead.

#vasu-balakrishnan The code you could use for this is:
//IEnumerable.untyped_to_typed grid.Children
//|> IEnumerable.iter (fun (ctrl : Control) -> ctrl.Margin <- thick)
for child in grid.Children do
(fun (child : Control) -> child.Margin <- thick) |> ignore

Related

How to use Akka.Streams.*.ConcatMany in F#?

I want to create a flow that creates a new source (it will be a persistence query) out of incoming elements, and then flattens the results. Something like this simplified example:
var z = Source.Single(1).ConcatMany(i => Source.Single(i));
this code compiles and works as expected. My problem is that when I translate it to F#:
let z = Source.Single(1).ConcatMany(fun i -> Source.Single(i))
I get an error saying
This expression was expected to have type
'IGraph<SourceShape<'a>,Akka.NotUsed>'
but here has type
'Source<int,Akka.NotUsed>'
I think that the cause of that is that F# handles co/contravariance differently than C# and cannot simply convert these generic specializations (https://github.com/fsharp/fslang-suggestions/issues/162), but I cannot figure out a way to make a convertion between an int and a SourceShape<int>. Is it possible to convert this example to F#?
Looking at the code on GitHub, it appears that Source<TOut, TMat> is a direct implementation of IGraph, so you should just be able to cast it:
public sealed class Source<TOut, TMat> : IFlow<TOut, TMat>, IGraph<SourceShape<TOut>, TMat>
let z = Source.Single(1).ConcatMany(fun i -> Source.Single(i) :> IGraph<SourceShape<int>,Akka.NotUsed>)
I think the biggest difference between the C# and F# usage is that C# will automatically do the upcast for you.
One workaround that I found is to use Akkling.Streams wrapper library:
open Akkling.Streams
let x =
Source.singleton 1
|> Source.collectMap(fun x -> Source.singleton x)
the question how to do this without Akkling remains open.

What is the syntax for resolving Thenable<'t> in F# using fable?

I'm working on a vscode extension written in F# using Fable to compile to javascript. Many of the api's return a promise. What is the syntax for for resolving a promise that have return types such as Thenable<string[]> for F#?
Here is an example of many of the api's for vscode: vscode api
Take a look at how Ionide does it:
https://github.com/ionide/ionide-vscode-helpers/blob/fable/Helpers.fs
https://github.com/ionide/ionide-vscode-helpers/blob/fable/Fable.Import.VSCode.fs
Basically, it looks like Ionide almost ignored the existence of Thenable<T> and converted every API call to a Promise<T> in their Fable bindings. They do have a pair of toPromise and toThenable functions in Helpers.fs, but I don't see those being used anywhere in the entire https://github.com/ionide/ionide-vscode-fsharp repository.
I don't have any personal experience with Fable, so if this isn't enough to answer your question, hopefully someone else will chime in with more information.
After some playing with the syntax, I was able to figure it out with the clue that rmunn gave with converting the Thenable to Promise.
module PromiseUtils =
let success (a : 'T -> 'R) (pr : Promise<'T>) : Promise<'R> =
pr?``then`` (unbox a) |> unbox
let toPromise (a : Thenable<'T>) = a |> unbox<Promise<'T>>
let toThenable (a : Promise<'T>) = a |> unbox<Thenable<'T>>
Using the utility module above, I was able to convert the functions that return Thenable to Promises so they could be resloved.
let result = commands.getCommands ()
|> PromiseUtils.toPromise
|> PromiseUtils.success (fun item ->
let firstOne = item.Item 1
console.log(firstOne))

How to use FileSystemWatcher in F#

I want to watch a directory for file changes (create, edit, rename, delete) and do something, such as calling a function, when a change is detected. From what I can tell, FileSystemWatcher should do this. However, there is no sample code for F# on the documentation page, and elsewhere on the web seems scarce as well.
From what I've found, the following is at least part of the answer:
let fileSystemWatcher = new FileSystemWatcher()
fileSystemWatcher.Path <- #"C:\temp" // I'm actually using a variable here
fileSystemWatcher.NotifyFilter <- NotifyFilters.LastWrite
fileSystemWatcher.EnableRaisingEvents <- true
fileSystemWatcher.IncludeSubdirectories <- true
fileSystemWatcher.Changed.Add(fun _ -> printfn "changed")
fileSystemWatcher.Created.Add(fun _ -> printfn "created")
fileSystemWatcher.Deleted.Add(fun _ -> printfn "deleted")
fileSystemWatcher.Renamed.Add(fun _ -> printfn "renamed")
That doesn't actually do anything, however. Some posts seem to have an Async loop to react to events, but if I use the code snippets from there F# tells me that Async.AwaitObservable is undefined.
I'd appreciate it if someone could provide a complete example of FileSystemWatcher's correct usage.
Works fine for me in FSI.
Drop the NotifyFilter bit - you're overwriting the default settings (which do include LastWrite anyway), and some of the events you care about are not being raised. NotifyFilter is an antiquated enum-flag-style field, so you can add a new value there like this:
watcher.NotifyFilter <- watcher.NotifyFilter ||| NotifyFilters.LastWrite
You don't need an async loop per se - in the example you linked to it just replaces the standard event handlers that you are already using. But if you want to use Async.AwaitObservable, look up FSharpx on nuget.

Mocked Interface with NSubstitute on F# does not allow Returns

I have the following code:
open NSubstitute
type MyClass()=
let myObject = Substitute.For<IMyInterface>()
do myObject.MyProperty.Returns(true)
do myObject.MyMethod().Returns(true)
On "Returns" (both) I get the error that is not defined. The equivalent C# code works without issue. Adding |> ignore at the end of the do lines does not help. Am I missing something there?
I know you wrote that adding |> ignore at the end doesn't help, but this compiles on my machine:
type IMyInterface =
abstract MyProperty : bool with get, set
abstract member MyMethod : unit -> bool
open NSubstitute
type MyClass() =
let myObject = Substitute.For<IMyInterface>()
do myObject.MyProperty.Returns(true) |> ignore
do myObject.MyMethod().Returns(true) |> ignore
I attempted to infer the definition of IMyInterface from the question; did I get it wrong?
So after I tried the code (Mark Seemann's, as to avoid my C# class) on VS2012, fsi, through direct compilation with fsc and on VS2013, the issue is clearly a VS2012 problem. The code works correctly with the other three.
Not sure yet if it is using a different version of F#. Will need further investigation. But at least, for now, on VS2012 I can use:
do SubstituteExtensions.Returns(myObject.MyProperty, true) |> ignore
It works as well when I need to pass parameters to methods.

What's wrong with the following FsCheck test

It's probably something very simple, but I'm new to FsCheck and not sure why the below raises the error it does ("Geneflect: type not handled System.Numerics.BigInteger")?
open System.Numerics
type NumericGenerator =
/// Generating BigIntegers (though only in the regular integer range for now)
static member BigInt() =
{ new Arbitrary<System.Numerics.BigInteger>() with
override x.Generator =
Arb.generate<int>
|> Gen.map (fun i -> new BigInteger(i)) }
[<Property>]
let ``Simple test`` (b: BigInteger) =
Arb.register<NumericGenerator> |> ignore
b + 1I = 1I + b
This is using FsCheck with xUnit integration.
FsCheck is trying to generate a BigInteger before calling your test, because the Arb.register call is in your test method itself. It then tries to do that via reflection, which fails.
You can tell FsCheck about your custom arbitrary instance by adding it as a argument to your property.
[<Property(Arbitrary=[|typeof<NumericGenerator>|])>]
Also, you can add the ArbitraryAttribute to the test's enclosing module to register that arbitrary instance for all the properties in the module. See https://github.com/fsharp/FsCheck/blob/master/tests/FsCheck.Test/Runner.fs for some examples.
One final tip - if you are generating a type that's easily converted to/from another already generated type, you can easily create a generate and a shrinker using the Arb.convert method. Something like:
Arb.Default.Int32() |> Arb.convert ...
shoud work.

Resources