Mapping a value to one of its subclasses - data-structures

I have a point and a class that extends that point with some extra behavior:
Point(x: Int, y: Int)
WeightedPoint(value: Double) extends Point
WeightedPoint uses the same hash and equals method as Point.
I can make a map of the point to itself like Point -> WeightedPoint and make it so that it automatically performs p = WeightedPoint(1,2,324.0); map.put(p,p). Afterwards I can do map.get(Point(1,2)) and get WeightedPoint(1,2,324.0) I cannot make a map of Point -> Double because the WeightedPoint needs access to its x and y coordinates as well as its value.
Does this relationship have a name? Is there a data structure or pattern that directly does this?

Related

F# is unable to infer type arguments after annotation

So I have some json response content represented as string and I want to get its property names.
What I am doing
let properties = Newtonsoft.Json.Linq.JObject.Parse(responseContent).Properties()
let propertyNames, (jprop: JProperty) = properties.Select(jprop => jprop.Name);
According to this answer I needed to annotate the call to the extension method, however, I still get the error.
A unique overload for method 'Select' could not be determined based on type information prior to this program point. A type annotation may be needed. Candidates: (extension) Collections.Generic.IEnumerable.Select<'TSource,'TResult>(selector: Func<'TSource,'TResult>) : Collections.Generic.IEnumerable<'TResult>, (extension) Collections.Generic.IEnumerable.Select<'TSource,'TResult>(selector: Func<'TSource,int,'TResult>) : Collections.Generic.IEnumerable<'TResult>
Am I doing something wrong?
First, the syntax x => y you're trying to use is C# syntax for lambda expressions, not F# syntax. In F#, the correct syntax for lambda-expressions is fun x -> y.
Second, the syntax let a, b = c means "destructure the pair". For example:
let pair = (42, "foo")
let a, b = pair // Here, a = 42 and b = "foo"
You can provide a type annotation for one of the pair elements:
let a, (b: string) = pair
But this won't have any effect on pair the way you apparently expect it to work.
In order to provide type annotation for the argument of a lambda expression, just annotate the argument, what could be simpler?
fun (x: string) -> y
So, putting all of the above together, this is how your line should look:
let propertyNames = properties.Select(fun (jprop: JProperty) -> jprop.Name)
(also, note the absence of semicolon at the end. F# doesn't require semicolons)
If you have this level of difficulty with basic syntax, I suggest you read up on F# and work your way through a few examples before trying to implement something complex.

Why is it that traits for operator overloading require ownership of self? [duplicate]

I made a two element Vector struct and I want to overload the + operator.
I made all my functions and methods take references, rather than values, and I want the + operator to work the same way.
impl Add for Vector {
fn add(&self, other: &Vector) -> Vector {
Vector {
x: self.x + other.x,
y: self.y + other.y,
}
}
}
Depending on which variation I try, I either get lifetime problems or type mismatches. Specifically, the &self argument seems to not get treated as the right type.
I have seen examples with template arguments on impl as well as Add, but they just result in different errors.
I found How can an operator be overloaded for different RHS types and return values? but the code in the answer doesn't work even if I put a use std::ops::Mul; at the top.
I am using rustc 1.0.0-nightly (ed530d7a3 2015-01-16 22:41:16 +0000)
I won't accept "you only have two fields, why use a reference" as an answer; what if I wanted a 100 element struct? I will accept an answer that demonstrates that even with a large struct I should be passing by value, if that is the case (I don't think it is, though.) I am interested in knowing a good rule of thumb for struct size and passing by value vs struct, but that is not the current question.
You need to implement Add on &Vector rather than on Vector.
impl<'a, 'b> Add<&'b Vector> for &'a Vector {
type Output = Vector;
fn add(self, other: &'b Vector) -> Vector {
Vector {
x: self.x + other.x,
y: self.y + other.y,
}
}
}
In its definition, Add::add always takes self by value. But references are types like any other1, so they can implement traits too. When a trait is implemented on a reference type, the type of self is a reference; the reference is passed by value. Normally, passing by value in Rust implies transferring ownership, but when references are passed by value, they're simply copied (or reborrowed/moved if it's a mutable reference), and that doesn't transfer ownership of the referent (because a reference doesn't own its referent in the first place). Considering all this, it makes sense for Add::add (and many other operators) to take self by value: if you need to take ownership of the operands, you can implement Add on structs/enums directly, and if you don't, you can implement Add on references.
Here, self is of type &'a Vector, because that's the type we're implementing Add on.
Note that I also specified the RHS type parameter with a different lifetime to emphasize the fact that the lifetimes of the two input parameters are unrelated.
1 Actually, reference types are special in that you can implement traits for references to types defined in your crate (i.e. if you're allowed to implement a trait for T, then you're also allowed to implement it for &T). &mut T and Box<T> have the same behavior, but that's not true in general for U<T> where U is not defined in the same crate.
If you want to support all scenarios, you must support all the combinations:
&T op U
T op &U
&T op &U
T op U
In rust proper, this was done through an internal macro.
Luckily, there is a rust crate, impl_ops, that also offers a macro to write that boilerplate for us: the crate offers the impl_op_ex! macro, which generates all the combinations.
Here is their sample:
#[macro_use] extern crate impl_ops;
use std::ops;
impl_op_ex!(+ |a: &DonkeyKong, b: &DonkeyKong| -> i32 { a.bananas + b.bananas });
fn main() {
let total_bananas = &DonkeyKong::new(2) + &DonkeyKong::new(4);
assert_eq!(6, total_bananas);
let total_bananas = &DonkeyKong::new(2) + DonkeyKong::new(4);
assert_eq!(6, total_bananas);
let total_bananas = DonkeyKong::new(2) + &DonkeyKong::new(4);
assert_eq!(6, total_bananas);
let total_bananas = DonkeyKong::new(2) + DonkeyKong::new(4);
assert_eq!(6, total_bananas);
}
Even better, they have a impl_op_ex_commutative! that'll also generate the operators with the parameters reversed if your operator happens to be commutative.

Why is only contravariance allowed for method input parameters according to the Liskov Substitution Principle?

I was trying to find good examples of why contra-variance is the only variance allowed for method input parameters according to the Liskov Substitution Principle, but until now none of the examples has completely answered ,y doubts.
I was trying to build a counter-example that could prove the statement above, but I am not sure about it. Suppose we have the following classes:
class Z {...}
class X extends Z {...}
class Y extends X {...}
class A {
void m(X x);
...
}
class B extends A {
void m(Y y); // Overriding inherited method m using covariance (by contradiction)
...
}
Now, suppose I have the following situation:
B b = new B();
A a = b; // Allowed because b is also an A object (B extends A)
Now, since the static type of a is A, theoretically we should be able to pass X objects to the method m on a (not sure what the LSP says about this):
a.m(new X());
At runtime (not sure what the LSP says about runtime and compile-time), on the other hand, this would fail, because a is actually pointing to a B object, but the method overridden in B m only accepts Y objects, which are of subtype X.
If we had allowed contra-variance instead, for example by overriding m in B by specifying the type of the parameter as Z or X, none of this would happen.
This is for now my (and my friend's) only explanation of why we are only allowed to use contra-variance for method parameters.
Is my explanation correct? Are there other situations that can explain this concept more in detail? Concrete examples are appreciated!

Mapping/translating an object to another in F#

I'm a beginner to F# and playing around with it, until I faced this problem. I searched for it but couldn't find anything. I want to mutate an object into another. I have Geolocation object With lots of properties, two of them the Latitude and Longitude. I want to create a new dynamic object but using a pipe or a select operator, with only that subset of properties
let customLocation = OtherPlace.Geolocation ....
how can I do this?
The best way to solve this sort of problem is to create a discriminated union with a single case. You could use a straight type alias, but you would lose a small amount of type safety. To define the type use:
type Loc = |LL of float * float
and then you can create instances with something like:
Something |> fun t -> LL(t.Latitude,t.Longitude)
or the simpler version:
LL(something.Latitude,something.Longitude)
let's say you have an array of OtherPlace.Geolocation
geoLocations : OtherPlace.Geolocation array
you can then, depending on your need :
use a tuple (which is just a special case of a record)
.
//of type (double * double) array
let g = geoLocations |> Array.map (fun x -> x.Latitude, x.Longitude)
create a record type (nb : a tuple is just a record with positional names)
.
type Position = {Latitude : double; Longitude : double}
//of type Position array
let g = geoLocations |> Array.map (fun x -> x.Latitude, x.Longitude)
For small local need, a tuple is better suited but can become unwieldy.
Records allow you to better structure the program
Union case should be used to differentiate between different things, that still represent some common concept.
For instance you could have the position to be expressed in different system
type GeoPosition = | LaTLong of double * double
| WGS84 of double * double
| ...
//of type GeoPosition array
let g = geoLocations |> Array.map (fun x -> LatLong (x.Latitude, x.Longitude))
PS : if you use F# 3.1 you have one additional sugar for naming union type fields as shown here

Does an equivalent function in OCaml exist that works the same way as "set!" in Scheme?

I'm trying to make a function that defines a vector that varies based on the function's input, and set! works great for this in Scheme. Is there a functional equivalent for this in OCaml?
I agree with sepp2k that you should expand your question, and give more detailed examples.
Maybe what you need are references.
As a rough approximation, you can see them as variables to which you can assign:
let a = ref 5;;
!a;; (* This evaluates to 5 *)
a := 42;;
!a;; (* This evaluates to 42 *)
Here is a more detailed explanation from http://caml.inria.fr/pub/docs/u3-ocaml/ocaml-core.html:
The language we have described so far is purely functional. That is, several evaluations of the same expression will always produce the same answer. This prevents, for instance, the implementation of a counter whose interface is a single function next : unit -> int that increments the counter and returns its new value. Repeated invocation of this function should return a sequence of consecutive integers — a different answer each time.
Indeed, the counter needs to memorize its state in some particular location, with read/write accesses, but before all, some information must be shared between two calls to next. The solution is to use mutable storage and interact with the store by so-called side effects.
In OCaml, the counter could be defined as follows:
let new_count =
let r = ref 0 in
let next () = r := !r+1; !r in
next;;
Another, maybe more concrete, example of mutable storage is a bank account. In OCaml, record fields can be declared mutable, so that new values can be assigned to them later. Hence, a bank account could be a two-field record, its number, and its balance, where the balance is mutable.
type account = { number : int; mutable balance : float }
let retrieve account requested =
let s = min account.balance requested in
account.balance <- account.balance -. s; s;;
In fact, in OCaml, references are not primitive: they are special cases of mutable records. For instance, one could define:
type 'a ref = { mutable content : 'a }
let ref x = { content = x }
let deref r = r.content
let assign r x = r.content <- x; x
set! in Scheme assigns to a variable. You cannot assign to a variable in OCaml, at all. (So "variables" are not really "variable".) So there is no equivalent.
But OCaml is not a pure functional language. It has mutable data structures. The following things can be assigned to:
Array elements
String elements
Mutable fields of records
Mutable fields of objects
In these situations, the <- syntax is used for assignment.
The ref type mentioned by #jrouquie is a simple, built-in mutable record type that acts as a mutable container of one thing. OCaml also provides ! and := operators for working with refs.

Resources