Can I overload the '=' operator for struct-typed arguments? - struct

I want to get a warning everywhere the equals operator '=' is used on struct-typed arguments. It seems that if I define this operator it does not overload, it just redefines '=' to only work for struct-typed arguments, which is not what I want.
[<Obsolete("Possible performance issue with '=' operator on structs. See https://github.com/dotnet/fsharp/issues/526.")>]
let inline (=) (x: ^T) (y: ^T) : bool when ^T: struct and ^T: (static member (=) : ^T * ^T -> bool) =
x = y
let a = obj()
let x = Guid.NewGuid()
let y = Guid.NewGuid()
a = a |> ignore // oh no - "A generic construct requires that the type 'obj' is a CLI or F# struct type."
x = y |> ignore // ok - gets desired warning
Can this be done in F# as is?
Update: found a possible workaround: simply use the [<NoEquality>] attribute on the affected structs; it does mean that all structs need to be annotated but at least it does help.

No, you cannot redefine a globally-scoped (i.e. non-member) function only for some cases. Once a function is in scope, it will always be used, there is no fallback to the previously defined one.

Related

Alloy changing comparison operators precedence for signatures

I have noticed Alloy's comparison operators precedence follows this order:
comparison negation operators: ! and not;
comparison operators: in, =, <, >, =<, =>.
A project I work in has defined two predicates mySyn and Semantics to evaluate Boolean expressions through these following signatures (myNotEquals, myEquals and myGreaterThan) built on Alloy's comparison operators, respectively (!=, = and >). Those are extending BExp abstract signature.
I would like to ask two questions (to simplify, I have omitted some pieces of code, by using ... symbol):
Does the evaluation of those signatures follow the original Alloy order? I mean myNotEquals comes first, next myEquals and finally, myGreaterThan?
Is that possible to change the precedence of those signatures whose are going to be evaluated, for instance myEquals comes first, next myGreaterThan and finally, myNotEquals?
mySyn predicate:
pred mySyn[...] {
...
, Semantics[evalC, evalB, evalA]
...
}
Semantics predicate:
pred Semantics[ ...] {
...
, evalB: BExp -> (State -> Bit)
...
}
Evaluating Boolean expressions
all b: myEquals, s: State | aritmethicExpr1[s] = aritmethicExpr2[s] implies evalB[b][s] = BitTrue else evalB[b][s] = BitFalse
all b: myNotEquals, s: State | aritmethicExpr1[s] != aritmethicExpr2[s] implies evalB[b][s] = BitTrue else evalB[b][s] = BitFalse
all b: myGreaterThan, s: State | aritmethicExpr1[s] > aritmethicExpr2[s] implies evalB[b][s] = BitTrue else evalB[b][s] = BitFalse
Thank you for your help :)

How to undestand functors in the Nix expression language?

I'm having a bit of trouble parsing this. But as I write it out, I think I may have it.
let add = { __functor = self: x: x + self.x; };
inc = add // { x = 1; };
in inc 1
First, is self a keyword like in many OO languages or is this just a regular name?
Secondly, I'm trying to understand what the multiple : are doing in the definition of __functor, but this is probably a failing of my basic familiarity with Nix expressions, but I guess what is happening is that both self and x are arguments to __functor, i.e., it looks like it is probably a curried function.
So really, __functor here is what fmap would be in Haskell, I think, and self (add) is the functor itself, and x: x + self.x is what the function mapped by fmap would be in Haskell.
self is not a keyword, just an ordinary parameter name. You are correct that the right-hand side of __functor is a curried function of two arguments. The Nix interpreter ensures that __functor is passed the appropriate value for self, at the call site inc 1; __functor is handled specially, even though it's not a keyword per se.
Your example is nearly the same as:
let add = a: b: a + b
inc = add 1
in inc 1
In a larger program it might be useful to be able to override add.x elsewhere.
As noted in the comments, Nix uses "functor" in the sense of an object (here, set) that can be used syntactically like a function.
Passing self this way is Nix's version of "Objects are closures". The technique is used many places in Nixpkgs, with & without the __functor feature, to get the usual benefits of Objects, including extension (~ structural subtyping) & late binding.

Split a string into an Array in Swift

I'm trying to write my first Swift program, and I know this question has been asked before, but the answers using split aren't working for me. I'm using Xcode 6.4 and Swift 1.2.
I have a String named line.
If I write
let inputs = split(line) {$0 = " "}
as suggested at Swift: Split a String into an array, I get the error message "Cannot invoke 'split' with an argument list of type (String, ()->)"
If I write
let inputs = split(line, {find(" ",$0) != nil}, allowEmptySlices: false)
as suggested at split now complains about missing "isSeparator", I get the error message, "Missing argument for parameter 'isSeparator' in call."
If I jump to the definition of split, I find
func split<S : Sliceable, R : BooleanType>(elements: S, maxSplit: Int = default, allowEmptySlices: Bool = default, #isSeparator: #noescape (S.Generator.Element) -> R) -> [S.SubSlice]
I don't understand what the type of the last parameter is, which is perhaps the root of my problem. Can you tell me how I should call split, and even better can you explain what the parameter type is? Why isn't the type simply (S)->R? I am getting the line from a generator that reads a file line-by-line, if that makes any difference.
for line:String in reader! {
let inputs = split(line) {$0 = " "}
...
}
As said in the comments to the question, the correct way is to use the == operator instead of =.
The type (S.Generator.Element) -> R) must be interpreted in the light of the definition of split:
func split<S : Sliceable, R : BooleanType>
(elements: S,
maxSplit: Int = default,
allowEmptySlices: Bool = default,
#isSeparator: #noescape (S.Generator.Element) -> R)
-> [S.SubSlice]
The type of split is a generic one: in other words, it is a function that can take as first parameter any value that satisfy a generic type (or protocol) subtype of Sliceable, like String, and return a result which must be a subtype of BooleanType (for instance true or false, which are instances of Bool). So the last parameter is a function which gets as parameter a type which is Element of Generator of S (for instance Character) and returns a value of type R. And {$0 == " "} is exactly a predicate of this type, that has an (implicit) parameter ($0), and check if it is equal to the character " ".

ForAll and filter with Iterator in OCL

I need to do 2 functions in OCL that work on collection: forAll and filter. The trick is I can only use iterator.
This is what I come with:
context Collection(T)::forAll(expr) : Boolean
body : self -> iterate(t: T, acc: Boolean = true | expr(t) and acc)
context Collection(T)::filter(expr) : Collection(T)
body : self -> iterate(t: T, acc: Collection(T) = {} | if expr(t) then acc->include(t) else acc endif
Please tell me if it's right or wrong.
Your definition of forAll is fine, indeed it is the same as given in section 11.9 (Mapping Rules for Predefined Iterator Expressions) of OCL Version 2.4.
The filter operation is equivalent to the select operation that is defined by OCL in almost the same terms as you did, with the following differences:
It should be acc->including(t) instead of acc->include(t).
Collection is an abstract type, then I suppose you cannot write acc:Collection(T) = {} because the actual type of acc would be undefined. Instead of that you could use Bag(T) = Bag{} (but in this case Set(T)::filter(expr) would return a Bag instead of a Set).
The OCL specification solves this issue by defining select separately for each collection type (then we have Set(T)::select(body):Set(T), Sequence(T)::select(body):Sequence(T), etc.) with a different accumulator type in each case.

Ocaml - empty reference

How to create a empty reference? I mean something lika as
let x = ref Null
or
let x = ref None
or
let x = ref ()
There is no such thing in ML. A value of type t ref always holds a value of type t. This way, the curse of null pointer exceptions is avoided.
If you really need a nullable reference then you have to create a reference of type t option ref:
let r : int option ref = ref None
...
r := Some 5
The type system then ensures that you don't forget to handle the None case, e.g. with a match:
match !r with
| Some n -> ...
| None -> (* What now? *)
You should very rarely need such a thing, though. If you find yourself wanting an option ref then you should first try to restructure the problem.
It's hard to tell what you're asking. There's nothing predefined named Null in OCaml. There is something named None, and indeed you can say let x = ref None. You can also say let x = ref (). However it's hard to imagine a case where you'd want to do this. Since () is the only value of its type, you could never set x to any other value. So there would be no reason to use a reference.
Here is a session showing how to use ref None.
# let x = ref None;;
val x : '_a option ref = {contents = None}
# x := Some 5;;
- : unit = ()
# x;;
- : int option ref = {contents = Some 5}
# x := None;;
- : unit = ()
# x;;
- : int option ref = {contents = None}
Generally speaking an option type like int option allows you to have either an int value (like Some 5) or no value (None). Using a reference like int option ref gives you a mutable value that you can change between these two.
It looks to me like you're trying to reproduce patterns that you use in other languages. If possible you should try to learn OCaml in its own terms.

Resources