Comparison of Languages (I)
by language I mean programming language...
As a cyber-multilinguist, I frequently get confused by how different languages implement a certain operation. It is String.startsWith()
in Java
while String.startswith()
in python
. I have to look up the document to find out the correct spelling everytime. Sometimes the problem is even worse, especially when it comes to dealing with regex
. Languages adopt their own idiomatic usages and it's the programmers' duty to take note.
Syntax
Destructuring Assignment
What do I do if the function returns a tuple or an array?
int a[2] = {1, 2};
auto [x,y] = a;
auto& [xr, yr] = a;
float x{};
char y{};
int z{};
std::tuple<float&,char&&,int> tpl(x, std::move(y), z);
const auto& [a, b, c] = tpl;
struct S {
mutable int x1 : 2;
volatile double y1;
};
S f();
const auto [x, y] = f();
a, b = [10, 20]
print(a)
print(b)
a_t, b_t = (10, 20)
print(a_t)
print(b_t)
c, _, *d = [10, 15, 20, 30]
print(c)
print(d)
c_t, _, *d_t = (10, 15, 20, 30)
print(c_t)
print(d_t)
a, b = b, a
print(a)
print(b)
let a, b;
[a, b] = [10, 20];
console.log(a);
console.log(b);
let c, d;
[c, , ...d] = [10, 15, 20, 30];
console.log(c);
console.log(d);
[a, b] = [b, a];
console.log(a);
console.log(b);
JavaScript supports object destructuring,
which could be quite useful. However, since this feature exists only in one language, we don't put it here.
Another useful syntax of JavaScript is the object initializer,
which allows shorthands like
let a = 1, b = 2, c = 3;
let d = {a, b, c};
Template String
How do I print a variable in a string?
from string import Template
t = Template('Hey, $name!')
let ts = t.substitute(name='Bob')
print(ts)
a, b = 1, 2
print(f"sum {a+b}")
let a = 1;
let b = 2;
console.log("sum ${a+b}") # sum 3
Decorators
Basic Libraries
Array
In C++
, there is vector
as well as the build-in array. vector
is the first choice in most circumstances. Also note that in many functional programming languages, using loop on arrays may be deprecated. Seek map
or reduce
whenever possible!
Push Array push is among the most frequent operations.
std::vector<int> arr;
arr.push_back(10032);
arr = []
arr.append(10032)
let arr = []
arr.push(10032)
arr = [1, 2, 3];
arr = [arr, 10032];
brr = [1, 2, 3]';
brr = [brr; 10032];
Regex
Pattern Search What do you do if you are given a string like "length = 16"
?
import re
config = "length = 16"
regex = re.compile(r'(?P<key>[a-z]+)([\s])*=([\s])*(?P<val>\d+)')
groups = re.match(regex, config).groupdict()
print(groups["key"])
print(groups["val"])
let config = "length = 16";
let regex = /(?<key>[a-z]+)([\s])*=([\s])*(?<val>[\d]+)/;
let groups = config.match(regex).groups;
console.log(groups.key);
console.log(groups.val);
JSON
How do you dump an object into JSON, and vice versa?
import json
data = json.loads('{"foo": "bar"}')
print(json.dumps(data))
let data = JSON.parse('{"foo": "bar"}');
console.log(JSON.stringify(data));
Request
How do you send a request and read the response?
from urllib import request
from bs4 import BeautifulSoup
import sys
req = request.Request(
"http://zechen.site/home",
data=None,
headers={
'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_10_1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/39.0.2171.95 Safari/537.36'
}
)
try:
page = request.urlopen(req)
soup = BeautifulSoup(page, "html.parser")
print(soup.select("#signInNotice"))
except Exception as err:
print(err, file=sys.stderr)
const urllib = require('urllib');
const jQuery = require( "jquery" );
const { JSDOM } = require( "jsdom" );
urllib.request('http://zechen.site/home', {
method: 'GET',
headers: {
'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_10_1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/39.0.2171.95 Safari/537.36'
}
}).then(function (result) {
const { window } = new JSDOM(result.data);
const $ = jQuery(window);
console.log($("#signInNotice").html());
}).catch(function (err) {
console.error(err);
});
Text Tasks
Number From String
For conversion in JavaScript, see parseInt vs unary plus, when to use which?