Play 2.0 form mapping constraint: Double not supported? - mapping

New to Play, looks like one can apply numeric constraint to Ints and Longs, but not Doubles.
Kind of a show stopper given that case classes with Double properties cannot be bound/unbound; i.e.
case class Foo(orderTotal: Double)
// no dice, need a Double but get an Int (same deal with longNumber)
val form = Form(mapping('orderTotal -> number)(Foo.apply)(Foo.unapply) )
Anyone got a workaround? Seems like an oversight, no? You'd think that Double would be a fairly common requirement...

see Julian's comment above, resolved in 2.1 snapshot...

Related

F#: How to examine content in a n-tuple and return true or false?

Consider this F# code:
let isSalary employee =
let (fName,lName,Occupation,Department,SalaryType,
HoursPerWeek, AnnualSalary, HourlyWage
) = employee
SalaryType = "Salary"
if(employee.SalaryType = SalaryType) then
true
else
false
Im getting errors in here, any fixes to it?
First things first, please post error messages and a much more specific question. Thanks! But luckily, I can about deduce the error messages from this problem.
Next, if you want to mutate SalaryType after you've deconstructed your employee 8-tuple, you should write using the mutable keyword:
let mutable (fName, lName, Occupation, Department, SalaryType,
HoursPerWeek, AnnualSalary, HourlyWage) = employee
But you shouldn't. This is explained further below.
Next problem: there is no dot notation (no tuple.member) for accessing members of a tuple. It's only possible through deconstruction. So you can't employee.SalaryType.
Here's what looks to be the crux of the problem, and it's a mistake I made many times when I was learning functional programming, and it's a difficult paradigm shift to adapt to. You should not be attempting to mutate data, or in this case, variables. Variables, or values as they are called in F#, shouldn't change, as a broad rule. Functions should be pure.
What this means is that any parameters you pass into a function should not change after leaving the function. The parameter employee should be the same after you return to the calling scope.
There's a few syntactical errors you've made that make it pretty much impossible for me to deduce what you're trying to do in the first place. Please include this in the question.
Also, one last nitpick. As you know, the last expression in an F# function is it's return value. Instead of using an if statement, just return the condition you're testing, like this:
let ...
...
employee.SalaryType = SalaryType <- but remember, you can't use dot notation on tuples; this is just an example
Please read more on
https://learn.microsoft.com/en-us/dotnet/fsharp/language-reference/

Double Linked List in Julia

I'm new to Julia language and I wanted to improve my understanding by implementing a double linked list.
Unfortunately it seems that there is no good existing library for this purpose.
The only good one is the single linked list (here).
There is one implementation of a double linked list (here). But this is 2 years old and I'm not sure if it is outdated or not. And it does not allow a real empty list. It is just a single element with a default value.
At the moment I would be able to implement the common stuff like push!, pop!, that's not the problem.
But I'm struggling with implementing a double linked list that could be empty.
My current approach uses Nullable for a optional value of the reference and value.
type ListNode{T}
prev::Nullable{ListNode{T}}
next::Nullable{ListNode{T}}
value::Nullable{T}
ListNode(v) = (x=new(); x.prev=Nullable{x}; x.next=Nullable{x}; x.value=Nullable(v); x)
ListNode(p, n, v) = new(p, n, v)
end
type List{T}
node::Nullable(ListNode{T})
List() = (start=new(Nullable(ListNode{T}())); node=start; start)
List(v) = (start=new(Nullable(ListNode{T}(v))); node=start; start)
end
But it seems like this is pretty ugly and inconvenient to work with.
My second approach would be to introduce a boolean variable (inside List{T}) which stores if a list is empty or not. Checking this boolean would me allow to simply handle push! and pop! to empty lists.
I tried to google a good solution but I didn't found one.
Can anyone give me a "julia style" solution for the double linked list?
Thanks,
felix
There is now a library containing various data structures, DataStructures.jl Some initial notes regarding the question. As of this writing, type is decrepitated. Instead, mutable struct should be used, for Julia 1.0 and beyond. Nullable is also decrepitated, and a Union of Nothing and the type in question can be used instead.
There exist a package called DataStructures.jl that provides what you need.
You can find a DoubleLinked list containing the functionality you need here:
mutable_list
Code snippets from the link above, defining a DoubleLinked list in Julia >= v 1.1:
mutable struct ListNode{T}
data::T
prev::ListNode{T}
next::ListNode{T}
function ListNode{T}() where T
node = new{T}()
node.next = node
node.prev = node
return node
end
function ListNode{T}(data) where T
node = new{T}(data)
return node
end
end
mutable struct MutableLinkedList{T}
len::Int
node::ListNode{T}
function MutableLinkedList{T}() where T
l = new{T}()
l.len = 0
l.node = ListNode{T}()
l.node.next = l.node
l.node.prev = l.node
return l
end
end
In addition to the DataStructures package, Chris Rackauckas' LinkedLists.jl is a good resource.
The source code is quite readable and you can always ask questions.

Testing collections with FSUnit.Xunit

I'm trying to test equality of two collections in F# using FSUnit (specifically its Xunit branch) but failing horribly so far.
I have a function that returns an array of certain structs and would like to test whether the returned array is correct. The code I'm testing is in C# so it so the function can't return native F# lists.
The most promising approach I've tried is following:
[<Fact>]
let SimpleTest() =
let parser = new ExpressionParser()
parser.ParseExpression "2" |> should equal [new ParsedItem("2", ParsedItemType.Value)]
...but it results in the the test failing because of:
"Message> FSUnit.Xunit+MatchException: Exception of type 'FsUnit.Xunit+MatchException' was thrown.
Expected value: Equals [(2)]
Actual: was [2]
I can see that it's because the type of native F# list doesn't match a native array but have honestly no idea (nor have I found anything in documentation) how to do it differently (other then creating native array beforehand and populating it one by one...).
I've also tried some other approaches but they usually wouldn't even compile.
PS: I'm completely new to both F# and Xunit so I might be missing something absolutely obvious.
EDIT: A workaround that actually works better was suggested in comments (comparing string representations instead of the objects themselves) and while I will use that in my actual code I'd still appreciate a true solution to my problem above.
Although you can't easily return F# lists from your C# code, one option is to return arrays. These have structural equality, so you can simply compare them to determine if they are equal to each other:
open System.Linq
let csharpArray = Enumerable.Range(0, 10).ToArray()
let fsharpArray = [| 0..9 |]
These two arrays are equal:
> csharpArray = fsharpArray;;
val it : bool = true
If you don't want to return arrays, you can also return IEnumerable<T>, and convert to either lists or arrays in F#:
> let csharpEnumerable = Enumerable.Range(0, 10);;
val csharpEnumerable : System.Collections.Generic.IEnumerable<int>
> csharpEnumerable |> Seq.toList = [0..9];;
val it : bool = true
For a more comprehensive to introduction to unit testing with F#, you may want to view my Pluralsight course on the topic.
Ok, I've found the answer and it's simpler than I thought it'd be. First off the assentation works well the problem was in syntax and me not bothering to read the documentation on how to create an array in F# and just guessing it.
There were two things wrong. First [new ParsedItem("2", ParsedItemType.Value)] doesn't create an array it creates a list. That in itself wouldn't be a problem for FSUnit's should equal but it's enough to make simple structural equality test using = fail.
The second thing that was wrong was that I didn't really compare with [new ParsedItem("2", ParsedItemType.Value)] I compared with [new ParsedItem("2", ParsedItemType.Value), new ParsedItem("+", ParsedItemType.Operator), new ParsedItem("3", ParsedItemType.Value)] and that actually creates a list containing one touple. And that - unsurprisingly - didn't assert well :).
Simply reading the documentation and learning that an array is supposed to be created [|new ParsedItem("2", ParsedItemType.Value); new ParsedItem("+", ParsedItemType.Operator); new ParsedItem("3", ParsedItemType.Value)|] fixed the issue.
Anyway, thanks for the comments and the other answer. Though they didn't answer my question they increased my knowledge about F# and gave me a new idea how to test :).

Swift numerics and CGFloat (CGPoint, CGRect, etc.)

I'm finding Swift numerics particularly clumsy when, as so often happens in real life, I have to communicate with Cocoa Touch with regard to CGRect and CGPoint (e.g., because we're talking about something's frame or bounds).
CGFloat vs. Double
Consider the following innocent-looking code from a UIViewController subclass:
let scale = 2.0
let r = self.view.bounds
var r2 = CGRect()
r2.size.width = r.size.width * scale
This code fails to compile, with the usual mysterious error on the last line:
Could not find an overload for '*' that accepts the supplied arguments
This error, as I'm sure you know by now, indicates some kind of impedance mismatch between types. r.size.width arrives as a CGFloat, which will interchange automatically with a Swift Float but cannot interoperate with a Swift Double variable (which, by default, is what scale is).
The example is artificially brief, so there's an artificially simple solution, which is to cast scale to a Float from the get-go. But when many variables drawn from all over the place are involved in the calculation of a proposed CGRect's elements, there's a lot of casting to do.
Verbose Initializer
Another irritation is what happens when the time comes to create a new CGRect. Despite the documentation, there's no initializer with values but without labels. This fails to compile because we've got Doubles:
let d = 2.0
var r3 = CGRect(d, d, d, d)
But even if we cast d to a Float, we don't compile:
Missing argument labels 'x:y:width:height:' in call
So we end up falling back on CGRectMake, which is no improvement on Objective-C. And sometimes CGRectMake and CGSizeMake are no improvement. Consider this actual code from one of my apps:
let kSEP : Float = 2.0
let intercellSpacing = CGSizeMake(kSEP, kSEP);
In one of my projects, that works. In another, it mysteriously fails — the exact same code! — with this error:
'NSNumber' is not a subtype of 'CGFloat'
It's as if, sometimes, Swift tries to "cross the bridge" by casting a Float to an NSNumber, which of course is the wrong thing to do when what's on the other side of the bridge expects a CGFloat. I have not yet figured out what the difference is between the two projects that causes the error to appear in one but not the other (perhaps someone else has).
NOTE: I may have figured out that problem: it seems to depend on the Build Active Architecture Only build setting, which in turn suggests that it's a 64-bit issue. Which makes sense, since Float would not be a match for CGFloat on a 64-bit device. That means that the impedance mismatch problem is even worse than I thought.
Conclusion
I'm looking for practical words of wisdom on this topic. I'm thinking someone may have devised some CGRect and CGPoint extension that will make life a lot easier. (Or possibly someone has written a boatload of additional arithmetic operator function overloads, such that combining CGFloat with Int or Double "just works" — if that's possible.)
Explicitly typing scale to CGFloat, as you have discovered, is indeed the way handle the typing issue in swift. For reference for others:
let scale: CGFloat = 2.0
let r = self.view.bounds
var r2 = CGRect()
r2.size.width = r.width * scale
Not sure how to answer your second question, you may want to post it separately with a different title.
Update:
Swift creator and lead developer Chris Lattner had this to say on this issue on the Apple Developer Forum on July 4th, 2014:
What is happening here is that CGFloat is a typealias for either Float
or Double depending on whether you're building for 32 or 64-bits.
This is exactly how Objective-C works, but is problematic in Swift
because Swift doesn't allow implicit conversions.
We're aware of
this problem and consider it to be serious: we are evaluating several
different solutions right now and will roll one out in a later beta.
As you notice, you can cope with this today by casting to Double.
This is inelegant but effective :-)
Update In Xcode 6 Beta 5:
A CGFloat can be constructed from any Integer type (including the
sized integer types) and vice-versa. (17670817)
I wrote a library that handles operator overloading to allow interaction between Int, CGFloat and Double.
https://github.com/seivan/ScalarArithmetic
As of Beta 5, here's a list of things that you currently can't do with vanilla Swift.
https://github.com/seivan/ScalarArithmetic#sample
I suggest running the test suite with and without ScalarArithmetic just to see what's going on.
I created an extension for Double and Int that adds a computed CGFloatValue property to them.
extension Double {
var CGFloatValue: CGFloat {
get {
return CGFloat(self)
}
}
}
extension Int {
var CGFloatValue: CGFloat {
get {
return CGFloat(self)
}
}
}
You would access it by using let someCGFloat = someDoubleOrInt.CGFloatValue
Also, as for your CGRect Initializer, you get the missing argument labels error because you have left off the labels, you need CGRect(x: d, y: d, width: d, height: d) you can't leave the labels out unless there is only one argument.

c++0x why are "auto" vars in Range-based for-loop passed to loop body as values, not references?

I had an bug cuz of this, and it made me wonder why it was designed that way.
I feel that it would be better that auto something:container would produce references, not values.
For eg:
int t[3]{11,22,33};
for(int& el:t2)
el*=2;
gives 22,44,66
int t[3]{11,22,33};
for(auto el:t2)
el*=2;
"does nothing".
auto in the case you describe deduced that the type was int. If you wanted to turn that into a reference you can use auto&.
If the C++ compiler would use special rules just because it is in a for loop the rules would extremely confusing.
auto i = t[1];
is the same as
int i = t[1];
The same case here, if you want a reference you have to specify that you want a reference.
auto always deduces a value type. This is the same mechanism as what happens in a template, such as template<typename F> void foo(T t).

Resources