not quite understand 'a option - ocaml

class window =
object
val mutable top_widget = (None : widget option)
method top_widget = top_widget
end
and widget (w : window) =
object
val window = w
method window = window
end;;
There are two things I do not understand:
(None : widget option) what does this mean? Also, in general how do we use 'a option?
(w : window) this means w is a parameter of class widget, which is of type window?

A value of type 'a option has two forms:
None
Some x
Where x is a value of type 'a.
For example here are two values of type int option:
None
Some 421
This is probably obvious, but the idea is that the type represents a value that might or might not be present. The value None represents an absent value.
Yes, the notation (w: window) means that the class widget has a parameter that's a window. When you create a widget it would look like this:
let mywidget = new widget mywindow in
. . .

Related

How to Define Something that Acts as a Dictionary of Unique Functions in F#?

It is my understanding that a Dictionary's elements must all be the same (ie: unit -> unit)
I need a way to add functions to an object, similar to a Dictionary, but my problem is that the functions have different Types. The only thing I can know for sure is that added functions will always follow a pattern of int -> 'T where 'T could be any Type. All functions in the object could be made to inherit from a shared type if needed. Here is a non-functioning example of how it would be used.
let myFunctions = Dictionary<int,int -> unit>()
let exampleFunction0 (x : int) : int = x + 1
let exampleFunction1 (x : int) : byte = (byte)x
let exampleFunction2 (x : int) : string[] = Array.create<string> 1 "test"
myFunctions.Add(0, exampleFunction0)
myFunctions.Add(1, exampleFunction1)
myFunctions.Add(2, exampleFunction2)
let randomNumber = System.Random().Next(3)
let result x = myFunctions.Item(randomNumber) x
It is important to note that which one of the functions that gets called is random and I cannot know it. The purpose of the dictionary is to hold the functions that will be called randomly. As in the examples, the results are not the same as I need the results to be different for each function. x will always be the same, but the result of the function will not.
The code will be in a library to be reused, so functions may be added that I will never see.
You need to unify the output types to make this work.
If all the types are known you should use a Discriminated Union.
type ReturnValues =
| Case0 of int
| Case1 of byte
| Case2 of string[]
let myFunctions = Dictionary<int,int -> ReturnValues>()
let exampleFunction0 (x : int) = x + 1 |> Case0
let exampleFunction1 (x : int) = (byte)x |> Case1
let exampleFunction2 (x : int) = Array.create<string> 1 "test" |> Case2
myFunctions.Add(0, exampleFunction0)
myFunctions.Add(1, exampleFunction1)
myFunctions.Add(2, exampleFunction2)
let randomNumber = System.Random().Next(3)
let result x : ReturnValues = myFunctions.Item(randomNumber) x
If you don't know all the types you can make all the return types obj (Dictionary<int,int -> obj>) using the box function or you can make all the return types implement a common interface.
What has ultimately solved the problem for me is to package together the Type and Object. This package is what the functions that will be added to the dictionary must return. This way there is a standard way for new types to be added after compilation.
open System.Collections.Generic
open System
// a package that can hold an object and its type
type package(x, y) =
member this.x : Type = x
member this.y : Object = y
//empty class for testing
type testClass() = class end
//custom types for testing
type fiy(x) =
member this.Value : string = x
type foe(x) =
member this.Value : testClass = x
//functions for testing
let func0 (x: int) : package = package(typeof<int>, x)
let func1 (x: int) : package = package(typeof<fiy>, fiy("potato"))
let func2 (x: int) : package = package(typeof<foe>, foe(testClass()))
let myFunctions = Dictionary<int, (int -> package)>()
//example use of adding a function
myFunctions.Add(0, (func0))
myFunctions.Add(1, (func1))
myFunctions.Add(2, (func2))
//pick a random number to test with; as we will have no idea which function will be ran
let randomNumber = System.Random().Next(3)
let pickedFunction x : package = (myFunctions.Item(randomNumber) x)
let ranFunction = pickedFunction 5 //just some filler number to test with
printfn "The type of the ranFunction is: %s" (ranFunction.x.ToString())

Testing interfaces with foq

I am trying to use Foq to testing an interface with Foq.
So far, all examples I have seen for this have been relatively simple, such as the following:
let users = [|{ID = 1; pass = true};{ID = 2; pass= false}|]
type IFoo =
abstract member Bar: int -> bool
//tests with Foq
let dataAccess =
Mock<IFoo>()
.Setup(fun x-> <# x.Bar(users.[0].ID) #>).Returns(users.[0].pass)
.Setup(fun x-> <# x.Bar(users.[1].ID) #>).Returns(users.[1].pass)
.Create()
The examples have been sourced from 'Testing with F# - Mikael Lundin'
I have also researched this through a bit of googling (this link was helpful - http://trelford.com/blog/post/Foq.aspx)
However, the real Interfaces I want to test are the following:
type IParameters =
abstract member ParameterDate : int->string->DateTime
type IDataSource =
abstract member MortParameters: IParameters
I have tried a number of different ways to test these (e.g. defining a function with a signature of int->string to be used as the input to the setup. Alternatively, having the return value as a string->DateTime and the Setup as just an integer.
My question is really the following: When testing interfaces using Foq, how can I extend the testing to interfaces with function signatures of any general length (e.g. a->b->c->d->e etc.)
Since ParameterDate a property with a function type, you could just set it up as a property that returns a lambda value. See an example of property set-up in Foq. This should be easy to modify for your case:
let instance =
Mock<System.Collections.IList>()
.Setup(fun x -> <# x.Count #>).Returns(1)
.Create()
However, I guess you would lose the ability to have a strict mock with fixed expectations on the function inputs.
To enforce only expected inputs for the function returned by the mock property you could provide a function like this:
fun i s ->
match i, s with
| 1, "" -> DateTime.Now
| _ -> failwith "Invalid mock input"
I would probably stop here, but if you're working with code where you need to verify a function was called, as opposed to just ensuring you get the correct output, you could add a helper like this:
type Verifiable<'a, 'b> (f : 'a -> 'b) =
let called = ref false
member this.Func x =
called := true
f x
member this.Verify() =
if not called.Value then failwith "Mock function was not called"
And here's how you would use it:
let parameterDateMock =
fun i s ->
match i, s with
| 1, "" -> DateTime.Now
| _ -> failwith "Unexpected mock input"
|> Verifiable
let parameters =
{ new IParameters with member this.ParameterDate i s = parameterDateMock.Func i s }
parameters.ParameterDate 1 ""
parameterDateMock.Verify()
Caveat: This only verifies the function was called with at least one parameter. It may have returned another function by currying and not actually run the code in the mock function body. To get around that you'd need a variation of the Verifiable class for every function arity and use the right one in each case.

if-then statements involving signals

I am getting stuck writing a simple if-then statement in Elm involving signals.
What if the conditional is itself a Signal type? I would like to change the Mouse Down example on the Elm website:
import Graphics.Element exposing (..)
import Mouse
main : Signal Element
main =
Signal.map show Mouse.isDown
It will either say True or False depending on whether the Mouse is up or down. What if I want it to say "Up" or "Down"? My Boolean function could say:
<!-- language: haskell -->
f : Bool -> String
f x =
if x then "↑" else "↓"
but when I change the main function I get a type mismatch.
<!-- language: haskell -->
main : Signal Element
main =
Signal.map show ( f Mouse.isDown)
Error #1:
The 2nd argument to function `map` has an unexpected type.
10| Signal.map show ( f Mouse.isDown)
As I infer the type of values flowing through your program, I see a conflict
between these two types:
Signal a
String
Error #2:
The 1st argument to function `f` has an unexpected type.
10| Signal.map show ( f Mouse.isDown)
As I infer the type of values flowing through your program, I see a conflict
between these two types:
Bool
Signal Bool
It's basically the same thing as with show :: Bool -> Element. You're not passing the Signal into that function, but rather you map the function over the Signal. It works the same with your f:
import Mouse
import Graphics.Element exposing (Element, show)
f : Bool -> String
f x = if x then "↑" else "↓"
updown : Signal String
updown = Signal.map f Mouse.isDown
main : Signal Element
main = Signal.map show updown
Or in short, with composition: main = Signal.map (show << f) Mouse.isDown.

Typing in ocaml methods

I was playing with method redefinition, and I found this silly example :
class a =
object
method get (x : a) = x
end
class b =
object
inherit a
method get (x : b) = x
end
I'm clearly specifying that I want the get method from the b class to take a b and return a b, but the method signature is a -> a. And if I do
(new b)#get(new a)
he's very happy, when he really shouldn't. After that I added something silly :
class a =
object
method get (x : a) = x
end
class b =
object
inherit a
method get (x : b) = x#foo(x)
method foo (x : a) = x
end
And I get Error: This expression has type b
It has no method foo
What on earth is happening ?
Taking the first example first: OCaml has structural typing of objects, not nominal typing. In other words, the type of an object is determined entirely by its methods (and their types). So the classes a and b are in fact the same type.
$ ocaml
OCaml version 4.00.0
# class a = object method get (x: a) = x end;;
class a : object method get : a -> a end
# class b = object inherit a method get (x: b) = x end;;
class b : object method get : a -> a end
# let a0 = new a;;
val a0 : a = <obj>
# let b0 = new b;;
val b0 : b = <obj>
# (a0: b);;
- : b = <obj>
# (a0: a);;
- : a = <obj>
# (b0: a);;
- : a = <obj>
# (b0: b);;
- : b = <obj>
#
(What I'm trying to show here is that both a0 and b0 are of type a and of type b.)
In the second example, I'd say you're trying to give a new type to the get method. When you override a method in OCaml, the parameter and return types need to be the same as in the parent class.
The error message seems unfortunate. My guess is that the compiler is believing you that type b is another name for type a.
One of OCaml's strengths is that it will infer types. If you leave off the : b for the parameter of get in class b, you get the following error instead:
This expression has type a. It has no method foo
This is a little more helpful, in that it shows (I think) that you're required to have type a for the parameter.
Side comment (forgive me): if you come to the OO part of OCaml from a mainstream OO language, it might strike you as strange. But if you learn the FP part of OCaml first, you might wonder why all the mainstream OO languages get so many things wrong :-). (Granted, everything is tradeoffs and there is no one right way to structure computation. But OCaml's OO subsystem is doing something pretty impressive.)

Standard ML: Naming datatypes of function arguments possible?

I'm new to ML and with to have a function that receives a special pre-defined datatype, and able to reference to its entire argument datatype, rather its components.
Here's a stupid example:
datatype frame = Frame of string list * string list
(* Type: fn : string * frame -> frame *)
val lookup_variable_value_in_frame =
fn (string(var), Frame(variables, values)) =>
...
Frame(variables, values)
... ;
1) I want to return the given frame. Must I build another Frame ?
2) I wish to pass the given frame to another function, must I provide a new Frame(variables, values) again ?
I wish I could write somthing like this:
val lookup_variable_value_in_frame =
fn (string(var), frame : Frame(variables, values)) => ...
then I'll be able to use the frame or its components .
Thank you.
Your datatype has already has a name, which is frame. You don't have to build another frame for returning or passing to another function. The first option is using explicit type annotation:
(* Type: fn : string * frame -> frame *)
val lookup_variable_value_in_frame =
fn (var: string, f: frame) =>
...
f
... ;
This option is not common, it should used only when you need types less generic than they are inferred by the type checker. Another option is using as keyword to make another binding to the value:
val lookup_variable_value_in_frame =
fn (var, f as Frame(variables, values)) =>
...(* using f, variables or values here *)
Note that there is no such thing like string(var) in SML, either use var or var: string for explicit type annotation.