I'm trying to set up EF Core with F#.
My DbContext looks like this
type MainContext(options : DbContextOptions<MainContext>) =
inherit DbContext(options)
[<DefaultValue()>] val mutable dokumenter : DbSet<Dokument>
member x.Dokumenter with get() = x.dokumenter and set v = x.dokumenter <- v
and in Startup.fs:
member this.ConfigureServices(services: IServiceCollection) =
services.AddDbContext<MainContext>(fun options -> options.UseInMemoryDatabase()) |> ignore
which gives the following compilation error:
No overloads match for method 'AddDbContext'. The available overloads are shown below (or in the Error List window).
What am I doing wrong?
Adding |> ignore after UseInMemoryDatabase() did the trick:
services.AddDbContext<MainContext>(fun options -> options.UseInMemoryDatabase() |> ignore) |> ignore
Related
I am new to Scala, how to extends one properties value from other object. Like in angular, angular.copy(obj1, obj2);
If I have two objects, obj1, obj2, both having the same property names. obj2's value would be overridden to obj1.
How to achieve this in Scala?
Unlike JavaScript, Scala does not allow you to add new properties to existing objects. Objects are created with a specific type and that type defines the properties on the object. If your objects are implemented as a case class then it is easy to make a copy of an object:
val obj = obj1.copy()
You can also update some of the fields of obj1 during the copy and leave others untouched:
val obj = obj1.copy(count=obj2.count)
This will create a new object with all the same values as obj1 except for the field count which will take the value from obj2.
It has been noted in the comments that in Scala you will typically create new objects from old ones, rather than modifying existing objects. This may seem cumbersome at first but it make it much easier to understand the behaviour of more complex code because you know that objects won't change under your feet.
Note on object in Scala vs JS
Note that object in Scala as a completely different concept from the usage in Javascript.
Scala deliberately is not using Prototype base inheritance.
So in short that this is not possible is a feature not a mssing capability of the language.
see https://docs.scala-lang.org/tour/singleton-objects.html
Solution : Use a Map to simulate protoype base inheritance/composition
You can use a Map to achieve a similar behaviour:
scala> val sayHello = () => "Hello"
sayHello: () => String = <function0>
scala> val obj1 = Map("sayHello" -> sayHello , "id" -> 99)
obj1: scala.collection.immutable.Map[String,Any] = Map(sayHello -> <function0>, id -> 99)
scala> val obj2 = Map("id" -> 1)
obj2: scala.collection.immutable.Map[String,Int] = Map(id -> 1)
scala> obj1 ++ obj2
res0: scala.collection.immutable.Map[String,Any] = Map(sayHello -> <function0>, id -> 1)
I have the following interface:
type IFactory<'TIn, 'TOut> =
abstract Create: 'TIn -> 'TOut
I am trying to write a ComposedFactory. The following appears to be correct syntax as VS is not complaining about it:
type ComposedFactory<'TIn, 'TMid, 'TOut>
(midFactory: IFactory<'TIn, 'TMid>,
outFactory: IFactory<'TMid, 'TOut>) =
let Create' =
midFactory.Create >> outFactory.Create
interface IFactory<'TIn, 'TOut> with
member __.Create x = Create' x
But the fact that I am defining "Create" twice feels stupid. I want the interface one only. How can I do that?
You can do this for sport:
type ComposedFactory<'TIn, 'TMid, 'TOut>
(midFactory: IFactory<'TIn, 'TMid>,
outFactory: IFactory<'TMid, 'TOut>) =
interface IFactory<'TIn, 'TOut> with
member __.Create x = (midFactory.Create >> outFactory.Create) x
But I can't call it preferable by any means to what you had before.
I can't figure out how to do what you want to do I'm afraid. I would guess that an implementation of an interface function explicitly requires the parameters to be specified in its definition.
The best alternative I can suggest to you is piping:
member __.Create x = x |> midFactory.Create |> outFactory.Create
Background: I am trying to expand my existing logging framework, which is currently a wrapper of static non-thread-safe methods over printfn and friends. My design goals are: having a generic interface ILog and concrete classes like Dbg, Log, Trace. I cannot use modules and functions, unfortunately, because I like to leverage the ConditionalAttribute on the methods.
I have a working approach that looks something like this:
type ILog<'T, 'U, 'V> =
abstract member log: 'T -> unit
abstract member log: 'U * 'V -> unit
type Dbg<'T, 'U, 'V when 'T :> Printf.StringFormat<string> and 'U :> Printf.StringFormat<'V -> string>>() =
static member inline _do_other_stuff() = "other stuff"
static member inline private _helper() =
printfn "%s %s" (Dbg<_,_,_>._do_other_stuff())
interface ILog<'T, 'U, 'V> with
[<Conditional("DEBUG")>] // removed from call site
member this.log(msg) = sprintf msg |> Dbg<_,_,_>._helper()
[<Conditional("DEBUG")>] // removed from call site
member this.log(fmt, a) = sprintf fmt a |> Dbg<_,_,_>._helper()
module TestMe =
let test() =
let dbg = new Dbg<_,_,_>() :> ILog<_,_,_>
dbg.log("test%i", 2)
Here, the compiler and syntax checker and coloring detects properly the dbg.log("test%i", 2) line, which is exactly what I want. It will also properly raise an error if I were to write "test%s" instead.
Now, if I take the above approach and expand it to create more overloads of the ILog.log method, this gets pretty hairy pretty quickly because of all the type annotations and the required use of syntax like Dbg<_,_,_>. Some of it can be hidden away, but still I figured there must be a better way.
One approach I tried, which seemed very FSharpish is:
type ILog =
abstract member log: _ -> unit
abstract member log: _ * _ -> unit
This compiles the interface and infers the type to be 'a0 and 'a0 -> 'a1 respectively (which seems wrong, why is the second log member getting the same 'a0?). But, I can't find any way of implementing such overly generic interface:
type Dbg() =
interface ILog with
member this.log v = v + 1 |> ignore // it won't infer int here
It raises:
The declared type parameter '?' cannot be used here, since the type parameter cannot be resolved at compile time.
Does F# 4.0 have a way of declaring interfaces in a more generic way, or am I stuck to having to declare them specifically (while this works, it is tedious).
I am playing a bit with F# interfaces, by creating a simple data access class.
The interface is:
type IUserAccess =
abstract member GetUsers : (dbSchema.ServiceTypes.Users -> bool) -> dbSchema.ServiceTypes.Users seq
abstract member GetAllUsers : unit -> dbSchema.ServiceTypes.Users seq
In the class, I am calling the methods in this way:
type UserAccess() =
let db = dbSchema.GetDataContext()
interface IUserAccess with
member this.GetUsers cond =
let query = query {
for row in db.Users do
select row }
query |> Seq.where cond
member this.GetAllUsers () =
(this:>IUserAccess).GetUsers (fun _ -> true)
What I'm a bit concerned with is the way I am calling GetAllUsers function, specifically with part (this:>IUserAccess). What is the simplest way of calling methods that are implemented within the same interface?
One simple option I can think of is creating GetUsers method directly within UserAccess() class and then calling it from the interface implementation of both GetUsers and GetAllUsers, but that means a new private method implemented, which I would like to avoid. Is there another option?
I think the solution by #vcsjones is probably the best option if you want to avoid defining a separate method directly inside the class. That said, declaring a separate method is actually not that ugly. You can use local definition using let binding (which is automatically compiled as a private method) and I think it makes the code look quite nice:
type UserAccess() =
let db = dbSchema.GetDataContext()
let getUsers cond =
let query = query {
for row in db.Users do
select row }
query |> Seq.where cond
interface IUserAccess with
member this.GetUsers cond = getUsers cond
member this.GetAllUsers () = getUsers (fun _ -> true)
I generally quite like this style, because it separates all the private implementation from the part of the definition where you're defining the public exposed API.
F# always implements interfaces explicitly, so your options are pretty much as you stated, but you can avoid redundant casting by introducing a let binding:
type IUserAccess =
interface
abstract member GetUsers : (obj -> bool) -> unit
abstract member GetAllUsers : unit -> unit
end
type Foo() as self =
let userAccess = self :> IUserAccess
interface IUserAccess with
member this.GetUsers(q : (obj -> bool)) : unit =
()
member this.GetAllUsers() =
userAccess.GetUsers(fun _ -> true)
I just simplified your interface and object so I could get something compiling real quick.
What's the more idiomatic way to write the following?
val starting_value = ...
val result1 = f1(startingValue)
val result2 = f2(result1)
...
val resultN = fN(resultN-1)
If starting_value were a list of items to which I wanted to apply these functions, I could write
starting_list.map(f1).map(f2)...map(fN)
I can fake this by doing something like
Some(starting_value).map(f1)....map(fN).get
or
List(starting_value).map(f1)....map(fN).head
but this seems unnecessarily confusing.
Note: This question seems related but seems to be about a downstream issue.
(f1 andThen f2 andThen ... fN) {
startingValue
}
Use the forward pipe operator. For example (for def f(s: String) = s.length):
scala> "abc" |> f |> 0.until
res16: scala.collection.immutable.Range = Range(0, 1, 2)
You can find it in Scalaz, but you can find its definition elsewhere as well.
You can define an extension class that is also a value class. A value class is a special Scala construct that wraps up a single value inside a new compile-time type but the same exact runtime object, thus avoiding any new memory allocation. The class would look like:
implicit class Piper[A](val x: A) extends AnyVal {
def |>[B](f: A => B) = f(x)
}
Now when you do:
startingValue |> f1 |> f2 |> ... |> fN
Scala implicitly wraps up the starting value and each intermediate value in a Piper object at compile time and applies the Piper object's |> method, passing the intermediate values forward. At runtime no extra memory or time costs are incurred.
via /u/Baccata64
You could as well consider wrapping you value into Try, and then applying map(fN) on it. Then you will have prove, that if any function will fail, you won't get unexpected exception. You can then match on Success/Failure and do some recovery or just printing exact failure.