What is the purpose of M.empty in Daml Map function? - daml

when am using Map function it requires to declare M.empty,if am missing into an error,what is definition behind out of this M.empty usage,how exactly Map function work in DAML.
Error getting like below.
**
could not Match Excepted type Map Text ([a])
with actual Type
Map Text ([A]) -> Map Text ([A]) **
when i added M.Empty it is not running into this Error.For my understanding can please give explanation for how Map works and what is the reason behind M.Empty

It would be easier to answer if you provided the erroneous code, but from what I can parse, it looks like you may be misunderstanding what Map.empty is. Map.empty is not a function, it is a value; specifically, it is a Map that has no content.
Maps are sets of key/value pairs. One way to construct the Map that you want is to start with an empty Map and then add each of the elements that you want, one by one. Here is an example:
module Main where
import qualified DA.TextMap as Map
testMaps = scenario do
let m1 = Map.empty
let m2 = Map.insert "United States" "USD" m1
let m3 = Map.insert "France" "EUR" m2
let m4 = Map.insert "United Kingdom" "GBP" m3
assert (Map.lookup "France" m3 == Some "EUR")
If, on the line
let m3 = Map.insert "France" "EUR" m2
you forgot m2, you would get the error message you are describing. What this error message means is "I was expecting to get a Map (the result of the Map.insert function call), but instead I got a function that expects a Map and returns another Map". This is because DAML has a feature called automatic currying; the function Map.insert is defined as taking a key, a value, and a Map, and returning a Map. But you can also think of it as taking a key, and returning a function that takes a value, which returns a function that takes a Map, which returns a Map. So if you're missing an argument, the specific expression is still valid, it just happens to return a function that still expects one more argument, rather than returning a value.

Related

What programming language has a colon "inside" and "after" the parameter of a function

I came across this function and I've been searching for the programming language that has this syntax:
function getDiscount(items: Item[]): number {
if(items.length === 0){
throw new Error("Items cannot be empty");
}
let discount = 0;
items.forEach(function(item) {
discount += item.discount;
})
return discount/100;}
The parameter is delimited by a colon (:), and then the parameter is followed by another colon. I tried to run the code on the console but I'm getting an error "Uncaught SyntaxError: Unexpected token ':'"
The closest that I could find is Python's function annotation, however, the parameter is followed by an arrow instead of a colon.
I would also like to know what the code on the first line means - the parameter and what follows the parameter. My understanding is that the argument that will be passed will be inserted into an array and the data type of what will be returned is a number. Please correct me if I'm wrong.
This code is written in TypeScript (https://www.typescriptlang.org), which is a superset of JavaScript.
TypeScript code is valid JavaScript with added types.
Actually, if you removed the type annotations you could run this code in browser console:
function getDiscount(items) {
if(items.length === 0){
throw new Error("Items cannot be empty");
}
let discount = 0;
items.forEach(function(item) {
discount += item.discount;
})
return discount/100;
}
TypeScript needs to be converted into JavaScript so it can be used in a browser or NodeJS. The conversion process is known as 'transpiling', which is similar to compiling but is more like transformation from one human readable language to another, rather than the typical conversion from a human readable to machine readable. (I updated this description as suggested by Caius Jard)
Type annotations in the definition of the function mean that it takes an array of items of type Item as an argument and returns type number.
From the code we can say that the type Item is an object which has at least one key, discount, of type number. This code will iterate over the array of Item's and return the sum of all discounts.

How to cast an `_InternalLinkedHashMap` created from json?

Sometimes, when traversing complex json files in Dart it would be nice if we could tell our editor what the expected structure is so that we can make best use of the editor's intelligent code completion features.
As a toy example, consider the script writer.dart:
import 'dart:convert' show json;
main() {
Map<String, num> myMap = {"a": 1, "b": 2, "c": 3};
print(json.encode(myMap));
}
Let's say we use writer.dart to create a json file:
dart writer.dart > data.json
We have another script, called reader.dart, that will read this file and ideally interpret the data as a Map<String, num> instance:
import 'dart:io' show File;
import 'dart:convert' show json;
main() async {
Map<String, num> myMap = json.decode(await File("data.json").readAsString());
}
This script, however, throws the exception type '_InternalLinkedHashMap<String, dynamic>' is not a subtype of type 'Map<String, num>'.
Naive attempts such as the following also don't work:
var myMap = json.decode(await File("data.json").readAsString()) as Map<String, num>;
Of course we could do something like:
var myMap = Map<String, num>();
(json.decode(await File("data.json").readAsString()) as Map).forEach((k, v) {
myMap[k] = v;
});
But that's really ugly!
What is the best way to let the editor know what data structure to expect when parsing json?
The map returned by json.decode is a mutable Map<String, Object>. In this case, you know that the values are all num instances, but the JSON decoder didn't know that. Even if it did, since the value is mutable, the decoder has to assume someone might want to add any object to the map later.
There are two basic ways to get a map with a stricter type from another map: Copying to a new map (and checking the stricter type while copying), or wrapping/adapting the original map (and checking the stricter type on every access).
You create a new map of whatever type you want by:
Map<String, num> newMap = Map<String, num>.from(originalMap);
The argument to Map.from is a Map<dynamic, dynamic>, so it really accepts any map, and it then copies each entry into a new map with the requested type.
If you change the original map after making the copy, the copy is unaffected.
The other option is to wrap using:
Map<String, num> wrappedMap = originalMap.cast<String, num>();
This does nothing up-front. Every time you try to look something up in the wrapped map, it checks the argument type and return value type against the types you asked for. If you change the original map, the wrapped map changes as well (which is another reason it can't just check the types once, it has to check every time in case the value has changed).
The two approaches have different efficiency trade-offs. Copying everything takes space and time. Checking types takes time too. If you plan to use the same map over and over again, or to modify it, then creating a new map is probably more efficient. If not, Map.cast is easier to use.
(Although this answer seems obvious in retrospect, I was struggling with this for a while and only figured it out while composing the above question on this site. Just in case it is useful to anyone else, I went ahead and posted the question anyway.)
Just use the from constructor!
var myMap = Map<String, num>.from(json.decode(await File("data.json").readAsString()));

Dynamic Function Call in FSharp

Is it possible to take an FSharp function and convert it to a Dynamic function, alternatively is something like this coming to FSharp in the future?
let func (a:int) (b:int) : int =
a + b
let dynamicFunc = FSharpFunc.ToDynamicFunc(func)
let argumentList = [1; 2]
let object = dynamicFunc argumentList
let result = object :?> int
It appears that you currently have to fall back to standard reflection (like this: calling a F# function by name) however, this approach seems very brittle. Mainly because there's no real guarantee it works, and you have to know what's going on under the covers.
Something like this could be used to wrap any function and do things dynamically.
let wrapFun (x:'f) : 'f =
let args = FSharp.Reflection.FSharpType.GetFunctionElements <| x.GetType()
let runner (any:obj list) : obj =
// Do extra things
FSharpFunc.DynamicInvoke x
FSharp.Reflection.FSharpValue.MakeFunction (typeof<'f>, runner) :?> 'f
F# does support the dynamic call operator. But you must implement yours. Here is a sample Implementation taken from http://www.fssnip.net/2U/title/Dynamic-operator-using-Dynamic-Language-Runtime
// Reference C# implementation of dynamic operations
#r "Microsoft.CSharp.dll"
open System
open System.Runtime.CompilerServices
open Microsoft.CSharp.RuntimeBinder
// Simple implementation of ? operator that works for instance
// method calls that take a single argument and return some result
let (?) (inst:obj) name (arg:'T) : 'R =
// TODO: For efficient implementation, consider caching of call sites
// Create dynamic call site for converting result to type 'R
let convertSite =
CallSite<Func<CallSite, Object, 'R>>.Create
(Binder.Convert(CSharpBinderFlags.None, typeof<'R>, null))
// Create call site for performing call to method with the given
// name and a single parameter of type 'T
let callSite =
CallSite<Func<CallSite, Object, 'T, Object>>.Create
(Binder.InvokeMember
( CSharpBinderFlags.None, name, null, null,
[| CSharpArgumentInfo.Create(CSharpArgumentInfoFlags.None, null);
CSharpArgumentInfo.Create(CSharpArgumentInfoFlags.None, null) |]))
// Run the method call using second call site and then
// convert the result to the specified type using first call site
convertSite.Target.Invoke
(convertSite, callSite.Target.Invoke(callSite, inst, arg))
You'd be able to use it as follows
// Dynamically invoke 'Next' method of 'Random' type
let o = box (new Random())
let a : int = o?Next(10)
As for the params you'd have to pass them as a Tuple something like
target?method(param1, param2) that would mean that the target method processes its argument as a Tuple and as such, some pattern matching may or may not be involved

JSON.parse and JSON.stringify are not idempotent and that is bad

This question is multipart-
(1a) JSON is fundamental to JavaScript, so why is there no JSON type? A JSON type would be a string that is formatted as JSON. It would be marked as parsed/stringified until the data was altered. As soon as the data was altered it would not be marked as JSON and would need to be re-parsed/re-stringified.
(1b) In some software systems, isn't it possible to (accidentally) attempt to send a plain JS object over the network instead of a serialized JS object? Why not make an attempt to avoid that?
(1c) Why can't we call JSON.parse on a straight up JavaScript object without stringifying it first?
var json = { //JS object in properJSON format
"baz":{
"1":1,
"2":true,
"3":{}
}
};
var json0 = JSON.parse(json); //will throw a parse error...bad...it should not throw an error if json var is actually proper JSON.
So we have no choice but to do this:
var json0= JSON.parse(JSON.stringify(json));
However, there are some inconsistencies, for example:
JSON.parse(true); //works
JSON.parse(null); //works
JSON.parse({}); //throws error
(2) If we keep calling JSON.parse on the same object, eventually it will throw an error. For example:
var json = { //same object as above
"baz":{
"1":1,
"2":true,
"3":{}
}
};
var json1 = JSON.parse(JSON.stringify(json));
var json2 = JSON.parse(json1); //throws an error...why
(3) Why does JSON.stringify infinitely add more and more slashes to the input? It is not only hard to read the result for debugging, but it actually puts you in dangerous state because one JSON.parse call won't give you back a plain JS object, you have to call JSON.parse several times to get back the plain JS object. This is bad and means it is quite dangerous to call JSON.stringify more than once on a given JS object.
var json = {
"baz":{
"1":1,
"2":true,
"3":{}
}
};
var json2 = JSON.stringify(json);
console.log(json2);
var json3 = JSON.stringify(json2);
console.log(json3);
var json4 = JSON.stringify(json3);
console.log(json4);
var json5 = JSON.stringify(json4);
console.log(json5);
(4) What is the name for a function that we should be able to call over and over without changing the result (IMO how JSON.parse and JSON.stringify should behave)? The best term for this seems to be "idempotent" as you can see in the comments.
(5) Considering JSON is a serialization format that can be used for networked objects, it seems totally insane that you can't call JSON.parse or JSON.stringify twice or even once in some cases without incurring some problems. Why is this the case?
If you are someone who is inventing the next serialization format for Java, JavaScript or whatever language, please consider this problem.
IMO there should be two states for a given object. A serialized state and a deserialized state. In software languages with stronger type systems, this isn't usually a problem. But with JSON in JavaScript, if call JSON.parse twice on the same object, we run into fatal exceptions. Likewise, if we call JSON.stringify twice on the same object, we can get into an unrecoverable state. Like I said there should be two states and two states only, plain JS object and serialized JS object.
1) JSON.parse expects a string, you are feeding it a Javascript object.
2) Similar issue to the first one. You feed a string to a function that needs an object.
3) Stringfy actually expects a string, but you are feeding it a String object. Therefore, it applies the same measures to escape the quotes and slashes as it would for the first string. So that the language can understand the quotes, other special characters inside the string.
4) You can write your own function for this.
5) Because you are trying to do a conversion that is illegal. This is related to the first and second question. As long as the correct object types are fed, you can call it as many times as you want. The only problem is the extra slashes but it is in fact the standard.
We'll start with this nightmare of your creation: string input and integer output.
IJSON.parse(IJSON.stringify("5")); //=> 5
The built-in JSON functions would not fail us this way: string input and string output.
JSON.parse(JSON.stringify("5")); //=> "5"
JSON must preserve your original data types
Think of JSON.stringify as a function that wraps your data up in a box, and JSON.parse as the function that takes it out of a box.
Consider the following:
var a = JSON.stringify;
var b = JSON.parse;
var data = "whatever";
b(a(data)) === data; // true
b(b(a(a(data)))) === data; // true
b(b(b(a(a(a(data)))))) === data; // true
That is, if we put the data in 3 boxes, we have to take it out of 3 boxes. Right?
If I put my data in 2 boxes and take it out of 1, I'm not holding my data yet, I'm holding a box that contains my data. Right?
b(a(a(data))) === data; // false
Seems sane to me...
JSON.parse unboxes your data. If it is not boxed, it cannot unbox it. JSON.parse expects a string input and you're giving it a JavaScript object literal
The first valid call to JSON.parse would return an object. Calling JSON.parse again on this object output would result in the same failure as #1
repeated calls to JSON.stringify will "box" our data multiple times. So of course you have to use repeated calls to JSON.parse then to get your data out of each "box"
Idempotence
No, this is perfectly sane. You can't triple-stamp a double-stamp.
You'd never make a mistake like this, would you?
var json = IJSON.stringify("hi");
IJSON.parse(json);
//=> "hi"
OK, that's idempotent, but what about
var json = IJSON.stringify("5");
IJSON.parse(json);
//=> 5
UH OH! We gave it a string each time, but the second example returns an integer. The input data type has been lost!
Would the JSON functions have failed us here?
var json = JSON.stringify("hi");
JSON.parse(json);
//=> "hi"
All good. And what about the "5" ?
var json = JSON.stringify("5");
JSON.parse(json));
//=> "5"
Yay, the types have been preseved! JSON works, IJSON does not.
Maybe a more real-life example:
OK, so you have a busy app with a lot of developers working on it. It makes
reckless assumptions about the types of your underlying data. Let's say it's a chat app that makes several transformations on messages as they move from point to point.
Along the way you'll have:
IJSON.stringify
data moves across a network
IJSON.parse
Another IJSON.parse because who cares? It's idempotent, right?
String.prototype.toUpperCase — because this is a formatting choice
Let's see the messages
bob: 'hi'
// 1) '"hi"', 2) <network>, 3) "hi", 4) "hi", 5) "HI"
Bob's message looks fine. Let's see Alice's.
alice: '5'
// 1) '5'
// 2) <network>
// 3) 5
// 4) 5
// 5) Uncaught TypeError: message.toUpperCase is not a function
Oh no! The server just crashed. You'll notice it's not even the repeated calling of IJSON.parse that failed here. It would've failed even if you called it once.
Seems like you were doomed from the start... Damned reckless devs and their careless data handling!
It would fail if Alice used any input that happened to also be valid JSON
alice: '{"lol":"pwnd"}'
// 1) '{"lol":"pwnd"}'
// 2) <network>
// 3) {lol:"pwnd"}
// 4) {lol:"pwnd"}
// 5) Uncaught TypeError: message.toUpperCase is not a function
OK, unfair example maybe, right? You're thinking, "I'm not that reckless, I
wouldn't call IJSON.stringify or IJSON.parse on user input like that!"
It doesn't matter. You've fundamentally broken JSON because the original
types can no longer be extracted.
If I box up a string using IJSON, and then unbox it, who knows what I will get back? Certainly not you, and certainly not the developer using your reckless function.
"Will I get a string type back?"
"Will I get an integer?"
"Maybe I'll get an object?"
"Maybe I will get cake. I hope it's cake"
It's impossible to tell!
You're in a whole new world of pain because you've been careless with your data types from the start. Your types are important so start handling them with care.
JSON.stringify expects an object type and JSON.parse expects a string type.
Now do you see the light?
I'll try to give you one reason why JSON.parse cannot be called multiple time on the same data without us having a problem.
you might not know it but a JSON document does not have to be an object.
this is a valid JSON document:
"some text"
lets store the representation of this document inside a javascript variable:
var JSONDocumentAsString = '"some text"';
and work on it:
var JSONdocument = JSON.parse(JSONDocumentAsString);
JSONdocument === 'some text';
this will cause an error because this string is not the representation of a JSON document
JSON.parse(JSONdocument);
// SyntaxError: JSON.parse: unexpected character at line 1 column 1 of the JSON data
in this case how could have JSON.parse guessed that JSONdocument (being a string) was a JSON document and that it should have returned it untouched ?

Is there a way to "grep" for a keyword in a JavaScript object in Chrome Dev Tools?

I often work with large JavaScript objects and instead of manually opening and closing "branches", I would like to simply search for a particular string and show any key or value that matches.
Sort of like "grepping" for a keyword in a JavaScript object. Is this possible (especially in Chrome Dev Tool)?
Unfortunately I was hoping I could at least try the JSON.stringify() trick and then search on the raw JSON in a text editor, but I get the following error:
Uncaught TypeError: Converting circular structure to JSON
You can look at the object's keys and match against them:
function grepKeys(o, query){
var ret = {};
Object.keys(o).filter(function(key){
return key.includes(query);
}).forEach(function(key){ // can reduce instead
ret[key] = o[key]; // copy over
});
return ret;
}
Which'd let you return a partial object with all the keys that contain the string you specified. Note that this will not show any prototype keys but can be easily extended to allow it (by using a for... in instead of an Object.keys or by using recursion):
var o = grepKeys({buzz:5, fuzz:3, foo:4}, "zz");
o; // Object {buzz: 5, fuzz: 3}