Ze Chen

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; // creates e[2], copies a into e, then x refers to e[0], y refers to e[1]
auto& [xr, yr] = a; // xr refers to a[0], yr refers to a[1]

// ---

float x{};
char  y{};
int   z{};
 
std::tuple<float&,char&&,int> tpl(x, std::move(y), z);
const auto& [a, b, c] = tpl;
// a names a structured binding that refers to x; decltype(a) is float&
// b names a structured binding that refers to y; decltype(b) is char&&
// c names a structured binding that refers to the 3rd element of tpl; decltype(c) is const int

// ---

struct S {
    mutable int x1 : 2;
    volatile double y1;
};
S f();
 
const auto [x, y] = f(); // x is an int lvalue identifying the 2-bit bit field
                         // y is a const volatile double lvalue
a, b = [10, 20]
print(a) # 10
print(b) # 20

a_t, b_t = (10, 20)
print(a_t) # 10
print(b_t) # 20

c, _, *d = [10, 15, 20, 30]
print(c) # 10
print(d) # [20, 30]

c_t, _, *d_t = (10, 15, 20, 30)
print(c_t) # 10
print(d_t) # [20, 30]

a, b = b, a
print(a) # 20
print(b) # 10
let a, b;
[a, b] = [10, 20];
console.log(a); // 10
console.log(b); // 20

let c, d;
[c, , ...d] = [10, 15, 20, 30];
console.log(c); // 10
console.log(d); // [20, 30]

[a, b] = [b, a];
console.log(a); // 20
console.log(b); // 10

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) # 'Hey, Bob!'

a, b = 1, 2
print(f"sum {a+b}") # sum 3
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"]) # "length"
print(groups["val"]) # "16"
let config = "length = 16";
let regex  = /(?<key>[a-z]+)([\s])*=([\s])*(?<val>[\d]+)/;
let groups = config.match(regex).groups;

console.log(groups.key); // "length"
console.log(groups.val); // "16"
JSON

How do you dump an object into JSON, and vice versa?

import json

data = json.loads('{"foo": "bar"}')
# data = {'foo', 'bar'}
print(json.dumps(data))
# {"foo": "bar"}
let data = JSON.parse('{"foo": "bar"}');
// data = {foo: "bar"}
console.log(JSON.stringify(data));
// {"foo":"bar"}
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?

std::stoi('3.14')
+'3.14'

2021/1/24 21:00:48

0%

Uploaded successfully.

0%

Uploaded successfully.


0%

Uploaded successfully.

0%

Uploaded successfully.