sum(ofProperty: "amount") giving error in swift 5 - realm

I am using swift5 and I am trying to sum by property like this:
let total = realm.objects(Purchase.self).sum(ofProperty: "amount")
but i get this error:
Type of expression is ambiguous without more context
what can I do?

Probably the easist solution is to let the compiler know what kind of result the sum will be.
Like this
let total: Double = realm.objects(Purchase.self).sum(ofProperty: "orderProperty")
print(total)
This tells the compiler than total will always be a Double
As a side note, Double's are (generally) not a good type to work with for financial situations. Look into Decimal (akin to NSDecimal and Decimal128)
#Persisted var decimal: Decimal128
in newer versions

Related

How to set value to the child map in the father map in kotlin?

as title, I have the code:
val description= mutableMapOf(
"father2" to "123",
"father" to mutableMapOf<String,String>())
description["father"]["child"] = "child value"
if i try this: description["father"]["child"]="child value"
I will get the error:
Unresolved reference. None of the following candidates is applicable because of receiver type mismatch:
public inline operator fun <K, V> MutableMap<String!, String!>.set(key: String!, value: String!): Unit defined in kotlin.collections
public inline operator fun kotlin.text.StringBuilder /* = java.lang.StringBuilder */.set(index: Int, value: Char): Unit defined in kotlin.text
how can i do?
This is about typing (or lack of it).
The description map is created from two pairs, one from a String to a String, and the other from a String to a MutableMap<String, String>.  The keys are both String, so Kotlin will infer String for the type of key.  But what about the values?  They're two completely unrelated types, with no common superclass except Any.  So the type of description is inferred to be MutableMap<String, Any>.  (You can check that in e.g. the REPL.)
So, when you pull out a value, what can the compiler tell about it?  Almost nothing.  It's an Any, so the only thing you can be sure of is that it's not null.
That's why the compiler isn't treating that pulled-out value like a map; as far as it knows, it might not be a map!  (We know — but only because we can see what the map was initialised with, and that it's not modified since then, nor is the reference shared with any other objects or threads that could modify it.  But that's a relatively rare circumstance.)
Kotlin is a strongly-typed language, which means the compiler tracks the type of everything, and tries very hard not to let you do anything that could cause a runtime error.  Your code, if it compiled, would risk a ClassCastException any time the data didn't exactly match what you expected, which is hardly a route to good programs.
So, what can you do?
The safest thing would be to change your program so that you don't have any maps with unknown types of values.  Obviously, that depends on what your program is doing, so we can't make useful suggestions here.  But if your description were a MutableMap<String, MutableMap<String, String>>, then the compiler would know exactly what type everything was, and your intended code would compile and run fine.
The other main alternative would be to check what the value is before trying to treat it like a map.  One way to do this uses the as? safe-cast operator.  That checks whether a value is of a given type; if so, it's cast to that type; otherwise, it returns null.  You can then use the .? safe-call operator to call a method only if the value isn't null.  Putting that together:
(description["father"] as? MutableMap<String, String>)?.put("child", "child value")
If the value is as you expect, that will work fine; if not, it will do nothing and continue.
That's rather long-winded, but it will compile and run safely.  Alternatively, you could do the same thing in a more explicit way like this:
val child = description["father"]
if (child is MutableMap<String, String>))
child["child"] = "child value"
(Within the if, the compiler knows the type of child, and uses a a ‘smart cast’ to allow the putter call.)
That's even more long-winded, of course.  But that's what you get from trying to work against the type system :-)
(Oh, and by the way, I think the usual terminology for recursive data structures is ‘parent’ and ‘child’; I've not seen ‘father’ used that way before.)
Try this:
description["father"]?.put("child", "child value")
My current solution:
val description:MutableMap<String,Any> = mutableMapOf(
"father" to "123"
)
val father2 = mutableMapOf<String,String>()
father2.put("child", "child value")
description["father2"]=father2
You can try this:
val description = mutableMapOf<String?,MutableMap<String,String>?>
("father" to mutableMapOf<String,String>())
description.get("father")?.put("Key","Value")
println(description) // {father={Key=Value}}

Resolving Julia 0.4 deprecation of Uint64

I want to create a 2D array of Uint64s in Julia 0.4. This worked in 0.3:
s = 128
a = zeros(Uint64, s, s)::Array{Uint64,2}
It continues to compile but gives me the notice
WARNING: Base.Uint64 is deprecated, use UInt64 instead.
I don't know what this message means. I've tried googling the error message but haven't found anything helpful. What is an equivalent line of code that will not produce any warnings?
s = 128
a = zeros(UInt64, s, s)::Array{UInt64,2}
Watch out for capitals!
Doug's answer is correct, except that you can simplify it to
s = 128
a = zeros(UInt64, s, s)
You don't need the type annotation ::Array{UInt64,2}. Defining a = zeros(UInt64, s, s) will create a variable which knows its type.
Note that the Julia error message was telling you what you had to do -- replace Uint64 by UInt64. If you can think of a better way of rephrasing the message to be clearer, that would be useful to hear.
In general, type annotations are at best redundant when defining variables in Julia -- the type is automatically inferred from the type of the right-hand side, and this will be the type assigned to the variable being created.
Type annotations are used in Julia in two circumstances:
1. to define the type of variables inside a composite type
2. for multiple dispatch in function definitions, to specify which types a given method applies to.

LLVM converting a Constant to a Value

I am using custom LLVM pass where if I encounter a store to
where the compiler converts the value to a Constant; e.g. there is an explicit store:
X[gidx] = 10;
Then LLVM will generate this error:
aoc: ../../../Instructions.cpp:1056: void llvm::StoreInst::AssertOK(): Assertion `getOperand(0)->getType() == cast<PointerType>(getOperand(1)->getType())->getElementType() && "Ptr must be a pointer to Val type!"' failed.
The inheritance order goes as: Value<-User<-Constant, so this shouldn't be an issue, but it is. Using an a cast on the ConstantInt or ConstantFP has no effect on this error.
So I've tried this bloated solution:
Value *new_value;
if(isa<ConstantInt>(old_value) || isa<ConstantFP>(old_value)){
Instruction *allocInst = builder.CreateAlloca(old_value->getType());
builder.CreateStore(old_value, allocInst);
new_value = builder.CreateLoad(allocResultInst);
}
However this solution creates its own register errors when different type are involved, so I'd like to avoid it.
Does anyone know how to convert a Constant to a Value? It must be a simple issue that I'm not seeing. I'm developing on Ubuntu 12.04, LLVM 3, AMD gpu, OpenCL kernels.
Thanks ahead of time.
EDIT:
The original code that produces the first error listed is simply:
builder.CreateStore(old_value, store_addr);
EDIT2:
This old_value is declared as
Value *old_value = current_instruction->getOperand(0);
So I'm grabbing the value to be stored, in this case "10" from the first code line.
You didn't provide the code that caused this first assertion, but its wording is pretty clear: you are trying to create a store where the value operand and the pointer operand do not agree on their types. It would be useful for the question if you'd provide the code that generated that error.
Your second, so-called "bloated" solution, is the correct way to store old_value into the stack and then load it again. You write:
However this solution creates its own register errors when different type are involved
These "register errors" are the real issue you should be addressing.
In any case, the whole premise of "converting a constant to a value" is flawed - as you have correctly observed, all constants are values. There's no point storing a value into the stack with the sole purpose of loading it again, and indeed the standard LLVM pass "mem2reg" will completely remove such a sequence, replacing all uses of the load with the original value.

Trying to understand the SML option structure

Okay so I started learning SML for a class, and I'm stuck with the option structure.
What I have so far for this example:
datatype suit = spades|hearts|clubs|diamonds;
datatype rank = ace|two|three|...|j|q|k|joker;
type card = suit*rank;
My lecturer was trying to explain the use of the option structure by saying that not all cards necessarily have a suit; jokers don't have a suit associated with them.
So when designing a function getsuit to get the suit of a card, we have the following:
datatype 'a option = NONE | SOME of 'a;
fun getsuit ((joker,_):card):suit option = NONE
| getsuit ((_,s):card):suit option = SOME s;
But using emacs, I get two errors, one saying how the pattern and constraint don't agree,
pattern: rank * ?.suit
constraint: rank * suit
and the other saying how the expression type and the resulting types don't agree.
expression: ?.suit option
result type: suit option
This was the code provided by the lecturer so clearly they're not of much help if it results in errors.
What's the meaning of "?." and why does it show up? How would I correctly define this function?
Not really a problem with option as you've defined it.
You've got the order of suit and rank in your card patterns the wrong way:
Try:
datatype 'a option = NONE | SOME of 'a;
fun getsuit ((_, joker):card):suit option = NONE
| getsuit ((s, _):card):suit option = SOME s;
My version of ML probably prints errors differently so I'm not sure how to explain the the meaning of ?. etc. But it's simple enough if you take it bit by bit:
Try
(clubs, ace);
The interpreter (or emacs if that's what you're using) tells you the type is a product of a suit * rank. That's ML's type inference at work, but you can specify the type (you expect) like this:
(clubs, ace): suit*rank;
Or
(clubs, ace): card; (* Works, since card is defined as (suit*rank) *)
And you won't have any complaints. But obviously you would if you did
(clubs, ace): rank*suit;
Or
(clubs, ace): card; (* card is defined as (rank*) *)
You placed a constraint on the type of getsuit's argument (that it must be a card, or the compatible (suit*rank) product), but the pattern is of type (rank*?) or (?*rank), neither of which are compatible with (suit*rank).

Haskell function to get part of date as string

I have a beginner question about dates and String in Haskell.
I need to get part of date (year, month or day) as String in Haskell. I found out, that if I write the following two lines in GHCi
Prelude> now <- getCurrentTime
Prelude> let mon = formatTime defaultTimeLocale "%B" now
then mon is of type String. However, I am unable to put this in a function. I tried for instance the following:
getCurrMonth = do
now <- getCurrentTime
putStrLn (formatTime defaultTimeLocale "%B" now)
But this returns type IO () and I need String (also not IO String, only String).
I understand that do statement creates a monad, which I don't want, but I have been unable to find any other solution for getting date in Haskell.
So, is there any way to write a function like this?
Thanks in advance for any help!
If you want to return a String representing the current time, it will have to be in the IO monad, as the value of the current time is always changing!
What you can do is to return a String in the IO monad:
> getCurrMonth :: IO String
> getCurrMonth = do
> now <- getCurrentTime
> return (formatTime defaultTimeLocale "%B" now)
then, from your top level (e.g. in main), you can pass the String around:
> main = do
> s <- getCurrMonth
> ... do something with s ...
If you really want a pure function of that sort, then you need to pass in the time explicitly as a parameter.
import System.Locale (defaultTimeLocale)
import System.Time (formatCalendarTime, toUTCTime, getClockTime, ClockTime)
main = do now <- getClockTime
putStrLn $ getMonthString now
getMonthString :: ClockTime -> String
getMonthString = formatCalendarTime defaultTimeLocale "%B" . toUTCTime
Notice how getMonthString can be pure since the IO action getClockTime is performed elsewhere.
I used the old-time functions, because I was testing it out on codepad, which apparently doesn't have the newer time package. :( I'm new to the old time functions so this might be off a couple hours since it uses toUTCTime.
As Don said, there's no way to avoid using monads in this situation. Remember that Haskell is a pure functional language, and therefore a function must always return the same output given a particular input. Haskell.org provides a great explanation and introduction here that is certainly worth looking at. You'd also probably benefit from monad introduction like this one or a Haskell I/O tutorial like this one. Of course there are tons more resources online you can find. Monads can initially be daunting, but they're really not as difficult as they seem at first.
Oh, and I strongly advise against using unsafePerformIO. There's a very good reason it has the word "unsafe" in the name, and it was definitely not created for situations like this. Using it will only lead to bad habits and problems down the line.
Good luck learning Haskell!
You can't get just a String, it has to be IO String. This is because getCurrMonth is not a pure function, it returns different values at different times, so it has to be in IO.

Resources