OCaml/reason design modules - ocaml

I'm coming from a Javascript background & I'm trying to understand how I need to structure/build a program with Reason/Ocaml's module system.
As an exercise let's say I want to write this piece of javascript in OCaml/Reason (will compile it back to js through js_of_ocaml)
var TeaType = new GraphQLObjectType({
name: 'Tea',
fields: () => ({
name: {type: GraphQLString},
steepingTime: {type: GraphQLInt},
}),
});
How should I design my program to accomplish this?
Should I make a module which takes another module to produce a GraphQLObjectType in js through js_of_ocaml?
How would I structure this type that backs a GraphQLObjectType?
Tea.re
let name = "Tea";
let fields = /* what type should I make for this? Tea is
just one of the many graphql-types I'll probably make */
I mean fields is a thunk which returns a map that contains an unknown amount of fields. (every graphqlobject has different fields)
To what type does this map in OCaml/Reason, do I need to make my own?

Just for you to feel the flavor of OCaml, the direct (syntactic) translation would be:
let tea_type = GraphQL.Object.{
name = "Tea";
fields = fun () -> QraphQL.Field.[{
name = GraphQL.Type.{name : GraphQL.string }
steeping_time = GraphQL.Type.{name : QraphQL.int }
}]
}
Basically, I mapped js objects to OCaml's records. There are also objects in OCaml with methods and inheritance, but I think that records are still a closer abstraction. The records can be seen as a named tuple, and, of course, can contain functions. Modules, are more heavy weight abstractions, that is also a collection of fields. Unlike records, modules may contain types, other modules, and basically any other syntactic construction. Since types are removed at compile time, the runtime representation of a module is absolutely the same as the representation of records. Modules also define namespaces. Since OCaml records are defined by the names of their fields, it is always useful to define each records in its own module, e.g.,
module GraphQL = struct
let int = "int"
let string = "string"
module Type = struct
type t = {
name : string
}
end
module Field = struct
type t = {
name : string;
steeping_time : Type.t
}
end
module Object = struct
type t = {
name : string;
fields : unit -> Field.t list
end
end

Related

Nested structured search is Sourcegraph?

I would like to search Java annotations with another annotations inside. I don't know how many nested levels there are or I don't want to specify it. Finally, I would like to search for examples of #ApiImplicitParams with param type body and with #Example annotations inside.
But first I am trying to match anything nested.
First I searched for
#ApiImplicitParams(...)
and it found me somethind. The very first result is
#ApiImplicitParams({ #ApiImplicitParam(name = "foo", value = "List of strings", paramType = "body", dataType = "Foo") })
and has #ApiImplicitParam inside. Let's try to match it.
I tried
#ApiImplicitParams({#ApiImplicitParam(...) ...})
but it didn't find that case with one nesting and didn't find any cases with multiple #ApiImplicitParams inside.
How to accomplish?
Finally, I would like to search for examples of #ApiImplicitParams with param type body and with #Example annotations inside.
I believe the following query will meet your requirements here.
#ApiImplicitParams({...#ApiImplicitParam(...paramType = "body"...)...}) lang:Java
Some examples of matches --
#ResponseBody
#ApiImplicitParams({ #ApiImplicitParam(name = "foo", value = "List of strings", paramType = "body", dataType = "Foo") })
public Foo create(#RequestBody final Foo foo) {
nickname = "setLoggingSettings")
#ApiImplicitParams({
#ApiImplicitParam(
name = "Logging Config",
value = "Logging config to be updated",
required = true,
dataType = "com.yugabyte.yw.forms.PlatformLoggingConfig",
paramType = "body")
})
public Result setLoggingSettings() throws JoranException {
A note on this --
I don't know how many nested levels there are or I don't want to specify it.
The query provided above assumes one nested block, I'm afraid right now Sourcegraph doesn't have a good way to express an arbitrary level of nesting.
Hope that helps!

How to back a MutableList<Uri> field with a MutableList<String>

I have an interface that looks like that:
interface MyObject {
val id: String
val media: MutableList<Uri>
}
I would like to make an implementation of it where the media list is backed by a MutableList<String> instead of MutableList<Uri> (the reason I need that is explained in my long question here). The easy way is:
data class MyObjectPojo(
override val id: String,
val mediaStringList: MutableList<String>
) : Tale {
override val media: MutableList<Uri>
get() = mediaStringList.map { Uri.parse(it) } as MutableList<Uri>
}
But it's obviously inefficient (e.g. in order to get only the first element, a map operation would run for the whole list). I thought about get() = object : MutableList<Uri> {...}, But I realized I have to implement more then 20 members... Is there any nicer way to achieve that?
One option is to extend AbstractList, which could be as simple as:
val media = object : AbstractList<URL>() {
override val size get() = mediaStringList.size
override fun get(index: Int) = Uri.parse(mediaStringList[index])
}
That gives you a read-only view of the underlying mediaStringList: any changes to that are immediately reflected in the view.
Like most performance issues, it's a trade-off: it doesn't store any data itself, but needs to create a new Uri each time an item is retrieved.  So it's a good idea only when you need to save memory at the expense of extra processing; or when the list is likely to be big compared with the number of items retrieved.
If you want the view to be writable, you could instead extend AbstractMutableList, and override three more methods.  (That's left as an exercise :-)
PS. I'd suggest initialising media to this object, rather than creating it in a getter, as the latter will create a new view every time the getter is called, which is wasteful.  (If you were concerned about creating even a single view for each MyObjectPojo, you could wrap it in by lazy {…} so that it would only be created the first time it was needed — at the cost of some synchronisation.)

How to store array of strings into Realm instance using a Dictionary?

I am new to Realm and having this issue.
I am having a Dictionary like this
{
firstName : "Mohshin"
lastName : "Shah"
nickNames : ["John","2","3","4"]
}
and a class like this
class User: Object {
var firstName: String?
var lastName: String?
var nickNames: [String]?
}
While I am trying to insert values it is throwing an exception as below
Property 'nickNames' is declared as 'NSArray', which is not a supported RLMObject property type. All properties must be primitives, NSString, NSDate, NSData, NSNumber, RLMArray, RLMLinkingObjects, or subclasses of RLMObject.
See https://realm.io/docs/objc/latest/api/Classes/RLMObject.html for more information.
I have also tried
var nickNames = NSArray()
var nickNames = NSMutableArray()
But not working.Do I need to make the Nickname model class and create a property as follow or there's a way to do this ?
var nickNames = List<Nickname>()
UPDATE:
You can now store primitive types or their nullable counterparts (more specifically: booleans, integer and floating-point number types, strings, dates, and data) directly within RLMArrays or Lists. If you want to define a list of such primitive values you no longer need to define cumbersome single-field wrapper objects. Instead, you can just store the primitive values themselves.
Lists of primitive values work much the same way as lists containing objects, as the example below demonstrates for Swift:
class Student : Object {
#objc dynamic var name: String = ""
let testScores = List<Int>()
}
// Retrieve a student.
let realm = try! Realm()
let bob = realm.objects(Student.self).filter("name = 'Bob'").first!
// Give him a few test scores, and then print his average score.
try! realm.write {
bob.testScores.removeAll()
bob.testScores.append(94)
bob.testScores.append(89)
bob.testScores.append(96)
}
print("\(bob.testScores.average()!)") // 93.0
All other languages supported by Realm also supports lists of primitive types.
you can find more details here. https://academy.realm.io/posts/realm-list-new-superpowers-array-primitives/
class BlogPost: Object {
#objc var title = ""
let tags = List<String>()
convenience init(title: String, tag: String) {
self.init()
self.title = title
self.tags.append(tag)
}
}
more details here
Realm doesn't support model properties that are NSArrays, and currently doesn't support properties that are Lists of primitive types (such as Lists of strings). For now, you should create a Nickname model that wraps the nickname string, and then store a List<Nickname>, as in your sample code above.
This ticket on our GitHub repository tracks support for lists of primitives, although none of the comments from 2014 are particularly relevant anymore. You can follow that ticket if you want to be informed as to when that feature will become available.
(Also note that you should declare your list property as let, not var.)
Using List is pretty much the only way to do it. When you initialize the Nickname object (the realm object you created for using in List), you should provide an array for the value param, even if the value is actually just one string. For example:
let aNickName = Nickname(value:["John"])
That is why it was throwing an error saying "Invalid value 'John' to initialize object of type 'Nickname'".

Configuring C# out parameters with Foq in F#

I am using F# and Foq to write unit tests for a C# project.
I am trying to set up a mock of an interface whose method has an out parameter, and I have no idea how to even start. It probably has to do with code quotations, but that's where my understanding ends.
The interface is this:
public interface IGetTypeNameString
{
bool For(Type type, out string typeName);
}
In C# Foq usage for the interface looks like this:
[Fact]
public void Foq_Out()
{
// Arrange
var name = "result";
var instance = new Mock<IGetTypeNameString>()
.Setup(x => x.For(It.IsAny<Type>(), out name))
.Returns(true)
.Create();
// Act
string resultName;
var result = instance.For(typeof(string), out resultName);
// Assert
Assert.True(result);
Assert.Equal("result", resultName);
}
As for how to achieve that with F#, I am completely lost. I tried something along the lines of
let name = "result"
let instance = Mock<IGetTypeNameString>().Setup(<# x.For(It.IsAny<Type>(), name) #>).Returns(true).Create();
which results in the quotation expression being underlined with an error message of
This expression was expected to have type IGetTypeNameString -> Quotations.Expr<'a> but here has type Quotations.Expr<'b>
Without any indication what types a and b are supposed to be, I have no clue how to correct this.
:?>
(It gets even wilder when I use open Foq.Linq; then the Error List window starts telling me about possible overloads with stuff like Action<'TAbstract> -> ActionBuilder<'TAbstract>, and I get even loster....)
Any assistance or explanation greatly appreciated!
Edit:
So, as stated here, byref/out parameters can not be used in code quotations. Can this be set up at all then in F#?
Foq supports setting up of C# out parameters from C# using the Foq.Linq namespace.
The IGetTypeNameString interface can be easily setup in F# via an object expression:
let mock =
{ new IGetTypeNameString with
member __.For(t,name) =
name <- "Name"
true
}
For declarations that have no analog in F#, like C#'s protected members and out parameters, you can also use the SetupByName overload, i.e.:
let mock =
Mock<IGetTypeNameString>()
.SetupByName("For").Returns(true)
.Create()
let success, _ = mock.For(typeof<int>)

How to write tests with mocks using f#

I'd like to write F# unit test with mock objects. I'm using NUnit.
But unfortunately I couldn't find any examples.
Here's an example of the code under test:
type ICustomer = interface
abstract Id: int with get
abstract Name: string with get
abstract CalculateBalanceWithDiscount: decimal -> decimal
end
type Customer = class
val id: int
val name: string
val balance: decimal
new(id, name, balance) =
{id = id; name = name; balance = balance}
interface ICustomer with
member this.Id
with get () = this.id
member this.Name
with get () = this.name
member this.CalculateBalanceWithDiscount discount =
this.balance - (discount * this.balance)
end
end
As a side-note, you can use implicit constructor syntax to make your class declaration a bit nicer. You can also simplify readonly properties, because you can omit with get():
// F# infers that the type is an interface
type ICustomer =
abstract Id : int
abstract Name : string
abstract CalculateBalanceWithDiscount : decimal -> decimal
// Parameters of the implicit constructor are autoamtically
// accessible in the body (they are stored as fields)
type Customer(id:int, name:string, balance:decimal) =
interface ICustomer with
member this.Id = id
member this.Name = name
member this.CalculateBalanceWithDiscount(discount) =
balance - (discount * balance)
Regarding testing - do you have any example of what you're trying to achieve? I'm sure we can help for example with translating code from C#. Or what kind of tests would you like to write using mocking?
In general, a nice thing about F# and functional languages is that you can usually test code more easily without using any mocks. Functional programs are written in a different style:
In functional programming, a function takes all it's inputs as arguments and the only thing that it does is that it calculates and returns some result. This is also true for methods of immutable object types - they do not modify any state of any objects
Mocks are typically used for two purposes:
To verify that the tested operation performed some call to a method of a referenced object e.g. prod.Update(newPrice) to update the state of the object. However, in functional programming the method should instead return the new state as the result - so you don't need mock object. Just check whether the new returned state is what you expected.
To load create a fake component of the application, for example instead of loading data from the database. Again, a purely functional function should take all it's inputs as arguments. This means that you don't need to create a mock object - you just call the function with some test data as argument (instead of data loaded from database).
In summary, this means that in a well-designed functional program, you should be able to write all unit tests simply as checks that verify that some function returns the expected result for the expected arguments. Of course, this isn't strictly true in F#, because you may need to interoperate with other impure .NET components (but that can be answered only if you give a more specific example).
You don't need to create a class in order to create mocks:
/// customer : int -> string -> decimal -> ICustomer
let customer id name balance =
{new ICustomer with
member this.Id = id
member this.Name = name
member this.CalculateBalanceWithDiscount discount =
balance - (discount * balance) }