🔰

【随時更新】主要プログラミング言語8種チートシート

2023/04/07に公開

はじめに

  • 個人的に主要言語と思う8言語&スクリプト(python, JavaScript, Rust, Haskell, C++, C#, bash, PowerShell)のチートシートです
  • インデントのために全角空白を含んでます。コピペする場合は気を付けて下さい
  • ChatGPT(GPT-4)に書かせたコードなので一部変なコードがあるかもしれません
  • 動かない場合はChatGPTにコードと一緒に"<プログラミング名>で<大分類名>の<小分類名>をやろうと思うんだけど、このコードを修正して。"的なことを書けば大抵の場合修正してくれます

チートシート

スプレッドシート版(こちらのほうが見やすいです)

https://1drv.ms/x/s!AqxcPJT01sLlgdx8vuzZMu37vlSaaQ?e=OxJADc

記事版(中身はスプレッドシート版と同じです)

大分類 小分類 python JavaScript Rust Haskell C++ C# bash PowerShell
基礎 変数定義(ミュータブル) a=1 let a=1 let mut a=1 let a=1 int a=1 int a=1 $a=1 $a=1
基礎 変数定義(イミュータブル) なし const x = 1 let x = 1 let x = 1 const int x = 1 const int x = 1 readonly x=1 $x = 1
計算 二項演算子 result = 1 + 2 const result = 1 + 2; let result = 1 + 2; result = 1 + 2 int result = 1 + 2; int result = 1 + 2; result=$((1 + 2)) $result = 1 + 2
計算 論理演算子 result = True and False const result = true && false; let result = true && false; result = True && False bool result = true && false; bool result = true && false; result=$(true && false) $result = $true -and $false
大分類 小分類 python JavaScript Rust Haskell C++ C# bash PowerShell
比較演算子 等価 result = 1 == 2 const result = 1 == 2; let result = 1 == 2; result = 1 == 2 bool result = 1 == 2; bool result = 1 == 2; result=$((1 == 2)) $result = 1 -eq 2
比較演算子 不等価 result = 1 != 2 const result = 1 != 2; let result = 1 != 2; result = 1 /= 2 bool result = 1 != 2; bool result = 1 != 2; result=$((1 != 2)) $result = 1 -ne 2
比較演算子 大小比較 result = 1 < 2 const result = 1 < 2; let result = 1 < 2; result = 1 < 2 bool result = 1 < 2; bool result = 1 < 2; result=$((1 < 2)) $result = 1 -lt 2
条件分岐 if 文 if a > b:
  print("a > b")
else:
  print("a <= b")
if (a > b) {
  console.log("a > b");
} else {
  console.log("a <= b");
}
if a > b {
  println!("a > b");
} else {
  println!("a <= b");
}
if a > b then
  putStrLn "a > b"
else
  putStrLn "a <= b"
if (a > b) {
  std::cout << "a > b" << std::endl;
} else {
  std::cout << "a <= b" << std::endl;
}
if (a > b)
{
  Console.WriteLine("a > b");
}
else
{
  Console.WriteLine("a <= b");
}
if [ $a -gt $b ]; then
  echo "a > b"
else
  echo "a <= b"
fi
if ($a -gt $b) {
  Write-Host "a > b"
} else {
  Write-Host "a <= b"
}
大分類 小分類 python JavaScript Rust Haskell C++ C# bash PowerShell
繰り返し for 文 for i in range(5):
  print(i)
for (let i = 0; i < 5; i++) {
  console.log(i);
}
for i in 0..5 {
  println!("{}", i);
}
forM_ [0..4] $ \i ->
  print i
for (int i = 0; i < 5; i++) {
  std::cout << i << std::endl;
}
for (int i = 0; i < 5; i++)
{
  Console.WriteLine(i);
}
for i in {0..4}; do
  echo $i
done
for ($i = 0; $i-lt 5; $i++) {
  Write-Host $i
}
繰り返し while 文 i = 0
while i < 5:
  i += 1
let i = 0
while (i < 5) {
  i++;
}
let mut i = 0;
while i < 5 {
  i += 1;
}
i <- 0
while (i < 5) $ do
  i <- i + 1
int i = 0;
while (i < 5) {
  i++;
}
int i = 0;
while (i < 5) {
  i++;
}
i=0
while [ $i -lt 5 ]; do
  ((i++))
done
$i = 0
while ($i -lt 5) {
  $i++
}
関数 関数定義 def add(a, b):
  return a + b
function add(a, b) {
  return a + b;
}
fn add(a: i32, b: i32) -> i32 {
  a + b
}
add a b = a + b int add(int a, int b) {
  return a + b;
}
int Add(int a, int b)
{
  return a + b;
}
add() {
  echo $(($1 + $2))
}
function Add($a, $b) {
  return $a + $b
}
関数 関数呼び出し result = add(2, 3)
print(result)
let result = add(2, 3);
console.log(result);
}
let result = add(2, 3);
println!("{}", result);
}
let result = add 2 3
print result
int result = add(2, 3);
std::cout << result << std::endl;
}
int result = Add(2, 3);
Console.WriteLine(result);
}
result=$(add 2 3)
echo $result
$result = Add(2, 3)
Write-Host $result
大分類 小分類 python JavaScript Rust Haskell C++ C# bash PowerShell
関数 関数の引数 def greet(name):
  return f"Hello, {name}!"
function greet(name) {
  return Hello, ${name}!;
}
fn greet(name: &str) -> String {
  format!("Hello, {}!", name)
}
greet :: String -> String
greet name = "Hello, " ++ name ++ "!"
std::string greet(std::string name) {
  return "Hello, " + name + "!";
}
public static string Greet(string name) {
  return $"Hello, {name}!";
}
greet() {
  echo "Hello, $1!"
}
function Greet($name) {
  return "Hello, $name!"
}
関数 ラムダ関数 add = lambda x, y: x + y const add = (x, y) => x + y; let add = |x: i32, y: i32| x + y; add = \x y -> x + y auto add = [](int x, int y) { return x + y; }; Func<int, int, int> add = (x, y) => x + y; add() {
  echo $(($1 + $2))
}
$add = { param($x, $y) return $x + $y }
関数 ジェネレータ関数 def gen_func():
  yield 1
  yield 2
  yield 3
function* gen_func() {
  yield 1;
  yield 2;
  yield 3; }`
fn gen_func() -> impl Iterator<Item=i32> {
  vec![1, 2, 3].into_iter()
}
gen_func = [1, 2, 3] std::vector<int> gen_func() {
  return {1, 2, 3};
}
IEnumerable<int> GenFunc() {
  yield return 1;
  yield return 2;
  yield return 3; }`
gen_func() {
  echo 1
  echo 2
  echo 3
}
function Gen-Func {
  1, 2, 3
}
ファイル ファイルの読み込み with open('file.txt', 'r') as f:
  content = f.read()
fs = require('fs');
content = fs.readFileSync('file.txt', 'utf8');
}
use std::fs;
let content = fs::read_to_string("file.txt").unwrap();
}
content <- readFile "file.txt" std::ifstream file("file.txt");
std::string content((std::istreambuf_iterator<char>(file)), std::istreambuf_iterator<char>());
}
using (StreamReader sr = new StreamReader("file.txt"))
{
  string content = sr.ReadToEnd();
}
content=$(cat file.txt) $content = Get-Content -Path 'file.txt' -Raw
}
大分類 小分類 python JavaScript Rust Haskell C++ C# bash PowerShell
ファイル ファイルの書き込み with open('file.txt', 'w') as f:
  f.write('Hello, World!')
fs = require('fs');
fs.writeFileSync('file.txt', 'Hello, World!', 'utf8');
}
use std::fs::File;
use std::io::Write;
let mut file = File::create("file.txt").unwrap();
file.write_all(b"Hello, World!").unwrap();
}
writeFile "file.txt" "Hello, World!" std::ofstream file("file.txt");
file << "Hello, World!";
file.close();
}
using (StreamWriter sw = new StreamWriter("file.txt"))
{
  sw.Write("Hello, World!");
}
echo 'Hello, World!' > file.txt Set-Content -Path 'file.txt' -Value 'Hello, World!'
}
リスト リストの生成 lst = [1, 2, 3] let lst = [1, 2, 3]; let lst = vec![1, 2, 3]; lst = [1, 2, 3] std::vector<int> lst = {1, 2, 3}; List<int> lst = new List<int> { 1, 2, 3 }; lst=(1 2 3) $lst = @(1, 2, 3)
リスト リストの要素追加 lst.append(4) lst.push(4); lst.push(4); lst = lst ++ [4] lst.push_back(4); lst.Add(4); lst+=("4") $lst += 4
リスト リストの要素削除 lst.remove(2) lst.splice(lst.indexOf(2), 1); lst.retain(|&x| x != 2); lst = filter (/=2) lst lst.erase(std::remove(lst.begin(), lst.end(), 2), lst.end()); lst.Remove(2); lst=("${lst[@]/2}") $lst = $lst -ne 2
大分類 小分類 python JavaScript Rust Haskell C++ C# bash PowerShell
リスト リストの長さ取得 len([1, 2, 3]) [1, 2, 3].length; vec![1, 2, 3].len() length [1, 2, 3] std::vector<int> v = {1, 2, 3};
v.size();
int[] arr = {1, 2, 3};
arr.Length;
array=(1 2 3)
echo ${#array[@]}
@(1, 2, 3).Count
リスト リストのスライス my_list = [1, 2, 3, 4, 5]
sliced_list = my_list[1:4]
const my_list = [1, 2, 3, 4, 5];
const sliced_list = my_list.slice(1, 4);
let my_list = vec![1, 2, 3, 4, 5];
let sliced_list = &my_list[1..4];
my_list = [1, 2, 3, 4, 5]
sliced_list = take 3 (drop 1 my_list)
std::vector<int> my_list{1, 2, 3, 4, 5};
std::vector<int> sliced_list(my_list.begin() + 1, my_list.begin() + 4);
List<int> my_list = new List<int> {1, 2, 3, 4, 5};
List<int> sliced_list = my_list.GetRange(1, 3);
my_list=(1 2 3 4 5)
sliced_list=("${my_list[@]:1:3}")
$my_list = @(1, 2, 3, 4, 5)
$sliced_list = $my_list[1..3]
リスト ソート s=['a','d','c']
s.sorted()
let numbers = [3, 1, 4, 1, 5, 9, 2, 6, 5, 3, 5];
numbers.sort((a, b)=>(a - b));
let mut numbers = [3, 1, 4, 1, 5, 9, 2, 6, 5, 3, 5];
numbers.sort();
let numbers = [3, 1, 4, 1, 5, 9, 2, 6, 5, 3, 5]
let sortedNumbers = sort numbers
int numbers[] = {3, 1, 4, 1, 5, 9, 2, 6, 5, 3, 5};
int n = sizeof(numbers) / sizeof(numbers[0]);
std::sort(numbers, numbers + n);
int[] numbers = { 3, 1, 4, 1, 5, 9, 2, 6, 5, 3, 5 };
Array.Sort(numbers);
numbers=(3 1 4 1 5 9 2 6 5 3 5)
sorted=($(echo "${numbers[@]}" | tr ' ' '\n' | sort -n))
$numbers = 3, 1, 4, 1, 5, 9, 2, 6, 5, 3, 5
$sorted = $numbers | Sort-Object
文字列 文字列の結合 s1 = 'hello'
s2 = 'world'
s3 = s1 + ' ' + s2
let s1 = 'hello';
let s2 = 'world';
let s3 = s1 + ' ' + s2;
let s1 = String::from("hello");
let s2 = String::from("world");
let s3 = format!("{} {}", s1, s2);
s1 = "hello"
s2 = "world"
s3 = s1 ++ " " ++ s2
std::string s1 = "hello";
std::string s2 = "world";
std::string s3 = s1 + " " + s2;
string s1 = "hello";
string s2 = "world";
string s3 = s1 + " " + s2;
s1="hello"
s2="world"
s3="${s1} ${s2}"
$s1 = "hello"
$s2 = "world"
$s3 = $s1 + " " + $s2
大分類 小分類 python JavaScript Rust Haskell C++ C# bash PowerShell
文字列 文字列の分割 s = 'a,b,c'
lst = s.split(',')
let s = 'a,b,c';
let lst = s.split(',');
let s = "a,b,c";
let lst: Vec<&str> = s.split(',').collect();
s = "a,b,c"
lst = splitOn "," s
std::string s = "a,b,c";
std::vectorstd::string lst;
std::istringstream ss(s);
std::string token;
while (std::getline(ss, token, ',')) {
  lst.push_back(token);
}
string s = "a,b,c";
string[] lst = s.Split(',');
s="a,b,c"
IFS=',' read -ra lst <<< "$s"
$s = "a,b,c"
$lst = $s -split ','
文字列 文字列長取得 len("hello") "hello".length; "hello".len() length "hello" std::string s = "hello";
s.length();
"hello".Length; echo -n "hello" | wc -c ("hello").Length
文字列 文字列置換 "hello world".replace("world", "everyone") "hello world".replace("world", "everyone"); "hello world".replace("world", "everyone") substitute "world" "everyone" "hello world" std::string s = "hello world";
std::replace(s.begin(), s.end(), "world", "everyone");
"hello world".Replace("world", "everyone"); echo "hello world" | sed 's/world/everyone/' "hello world".Replace("world", "everyone")
文字列 文字列の大文字化 s = "hello"
upper_s = s.upper()
let s = "hello";
let upper_s = s.toUpperCase();
let s = "hello".to_string();
let upper_s = s.to_uppercase();
s = "hello"
upper_s = map toUpper s
std::string s = "hello";
std::transform(s.begin(), s.end(), s.begin(), ::toupper);
string s = "hello";
string upper_s = s.ToUpper();
s="hello"
upper_s="${s^^}"
$s = "hello"
$upper_s = $s.ToUpper()
大分類 小分類 python JavaScript Rust Haskell C++ C# bash PowerShell
文字列 文字列の小文字化 s = "HELLO"
lower_s = s.lower()
let s = "HELLO";
let lower_s = s.toLowerCase();
let s = "HELLO".to_string();
let lower_s = s.to_lowercase();
s = "HELLO"
lower_s = map toLower s
std::string s = "HELLO";
std::transform(s.begin(), s.end(), s.begin(), ::tolower);
string s = "HELLO";
string lower_s = s.ToLower();
s="HELLO"
lower_s="${s,,}"
$s = "HELLO"
$lower_s = $s.ToLower()
文字列 文字列の検索 text = "Hello, World!"
index = text.find("World")
const text = "Hello, World!";
const index = text.indexOf("World");
let text = "Hello, World!";
let index = text.find("World");
text = "Hello, World!"
index = Data.List.findIndex "World" text
std::string text = "Hello, World!";
size_t index = text.find("World");
string text = "Hello, World!";
int index = text.IndexOf("World");
text="Hello, World!"
index=$(echo "$text" | grep -b -o "World" | cut -d: -f1)
$text = "Hello, World!"
$index = $text.IndexOf("World")
文字列 文字列の逆順 text = "Hello, World!"
reversed_text = text[::-1]
const text = "Hello, World!";
const reversed_text = text.split("").reverse().join("");
let text = "Hello, World!";
let reversed_text = text.chars().rev().collect::<String>();
text = "Hello, World!"
reversed_text = reverse text
std::string text = "Hello, World!";
std::reverse(text.begin(), text.end());
string text = "Hello, World!";
char[] charArray = text.ToCharArray();
Array.Reverse(charArray);
string reversed_text = new string(charArray);
text="Hello, World!"
reversed_text=$(echo "$text" | rev)
$text = "Hello, World!"
$reversed_text = -join ($text[-1..-($text.Length)])
文字列 文字列の繰り返し text = "abc"
repeated_text = text * 3
const text = "abc";
const repeated_text = text.repeat(3);
let text = "abc";
let repeated_text = text.repeat(3);
text = "abc"
repeated_text = concat $ replicate 3 text
std::string text = "abc";
std::string repeated_text(text, 3);
string text = "abc";
string repeated_text = new StringBuilder().Insert(0, text, 3).ToString();
text="abc"
repeated_text=$(printf "%.0s$text" {1..3})
$text = "abc"
$repeated_text = $text * 3
大分類 小分類 python JavaScript Rust Haskell C++ C# bash PowerShell
文字列 文字列の一部取得 text = "abcde"
substring = text[1:4]
const text = "abcde";
const substring = text.slice(1, 4);
let text = "abcde";
let substring = &text[1..4];
text = "abcde"
substring = take 3 $ drop 1 text
std::string text = "abcde";
std::string substring = text.substr(1, 3);
string text = "abcde";
string substring = text.Substring(1, 3);
text="abcde"
substring=${text:1:3}
$text = "abcde"
$substring = $text.Substring(1, 3)
文字列 文字列の一部置換 text = "hello world"
replaced_text = text.replace("world", "python")
const text = "hello world";
const replaced_text = text.replace("world", "python");
let text = String::from("hello world");
let replaced_text = text.replace("world", "python");
text = "hello world"
replaced_text = replace "world" "python" text
std::string text = "hello world";
std::string replaced_text = text;
size_t pos = replaced_text.find("world");
if (pos != std::string::npos) { replaced_text.replace(pos, 5, "python"); }
string text = "hello world";
string replaced_text = text.Replace("world", "python");
text="hello world"
replaced_text="${text/world/python}"
$text = "hello world"
$replaced_text = $text.Replace("world", "python")
辞書 生成 d = {'a': 1, 'b': 2, 'c': 3} let d = {'a': 1, 'b': 2, 'c': 3}; let d = [("a", 1), ("b", 2), ("c", 3)].iter().cloned().collect(); d = [("a", 1), ("b", 2), ("c", 3)] std::map<std::string, int> d = {{"a", 1}, {"b", 2}, {"c", 3}}; Dictionary<string, int> d = new Dictionary<string, int> { { "a", 1 }, { "b", 2 }, { "c", 3 } }; declare -A d=( ["a"]=1 ["b"]=2 ["c"]=3 ) $d = @{ "a" = 1; "b" = 2; "c" = 3 }
辞書 要素の取得 value = d['a'] let value = d['a']; let value = d.get("a").unwrap(); value = lookup "a" d int value = d["a"]; int value = d["a"]; value="${d["a"]}" $value = $d["a"]
大分類 小分類 python JavaScript Rust Haskell C++ C# bash PowerShell
辞書 要素の追加 d['d'] = 4 d['d'] = 4; d.insert("d", 4); d = insert "d" 4 d d.insert(std::pair<std::string, int>("d", 4)); d.Add("d", 4); d+=( ["d"]=4 ) $d.Add("d", 4)
辞書 要素の削除 del d['a'] delete d['a']; d.remove("a"); d = delete "a" d d.erase("a"); d.Remove("a"); unset d["a"] $d.Remove("a")
エラー処理 try-except try:
  ...
except:
  ...
try {
  ...
} catch (error) {
  ...
}
match func() {
  Ok() => {...},
  Err() => {...},
}
case func of
  Left e -> ...
  Right r -> ...
try {
  ...
} catch (...) {
  ...
}
try {
  ...
} catch (Exception) {
  ...
}
if command; then
  ...
else
  ...
fi
try {
  ...
} catch {
  ...
}
数学 乱数生成 import random
random.randint(1, 10)
Math.floor(Math.random() * 10) + 1; use rand::Rng;
rand::thread_rng().gen_range(1..=10)
import System.Random
randomR (1, 10)
#include <random>
std::uniform_int_distribution<>(1, 10)(std::default_random_engine())
Random rnd = new Random();
rnd.Next(1, 11);
$((RANDOM % 10) + 1) Get-Random -Minimum 1 -Maximum 11
大分類 小分類 python JavaScript Rust Haskell C++ C# bash PowerShell
日付・時刻 現在時刻取得 import datetime
datetime.datetime.now()
new Date(); use chrono::Local;
Local::now()
import Data.Time.Clock
getCurrentTime
#include <ctime>
std::time(0)
DateTime.Now; date Get-Date
日付・時刻 時間差計算 from datetime import datetime, timedelta
delta = timedelta(days=1)
new_date = datetime.now() + delta
const date = new Date();
const newDate = new Date(date.getTime() + 86400000);
use chrono::{Duration, Utc};
let new_date = Utc::now() + Duration::days(1);
import Data.Time.Clock
new_date = addUTCTime (60 * 60 * 24) getCurrentTime
std::chrono::system_clock::time_point now = std::chrono::system_clock::now();
auto new_date = now + std::chrono::hours(24);
DateTime now = DateTime.Now;
DateTime new_date = now.AddHours(24);
new_date=$(date -d "+1 day" +"%Y-%m-%d") $now = Get-Date
$new_date = $now.AddDays(1)
クラス クラス定義 class Dog:
def bark(self):
  print("Woof!")
class Dog {
  bark() {
  console.log("Woof!");
  }
}
struct Dog;
impl Dog {
  fn bark(&self) {
  println!("Woof!");
  }
}
data Dog = Dog
bark :: Dog -> String
bark _ = "Woof!"
class Dog {
public:
  void bark() {
  std::cout << "Woof!" << std::endl;
  }
};
public class Dog
{
  public void Bark()
  {
  Console.WriteLine("Woof!");
  }
}
# クラスのような構造はシェルスクリプトにはないため、スキップします。 class Dog {
  [void] Bark() {
  Write-Host "Woof!"
  }
}
クラス クラスのインスタンス化 my_dog = Dog()
my_dog.bark()
let myDog = new Dog();
myDog.bark();
}
let my_dog = Dog;
my_dog.bark();
}
let myDog = Dog
putStrLn $ bark myDog
Dog myDog;
myDog.bark();
}
Dog myDog = new Dog();
myDog.Bark();
}
# クラスのような構造はシェルスクリプトにはないため、スキップします。 $myDog = [Dog]::new();
$myDog.Bark();
}
大分類 小分類 python JavaScript Rust Haskell C++ C# bash PowerShell
モジュール インポート import math import * as math from 'math'; use std::math; import Math #include <cmath> using System.Math; source math.sh Import-Module Math
モジュール 関数呼び出し result = math.sqrt(4) const result = math.sqrt(4); let result = f64::sqrt(4.0); result = sqrt 4 double result = std::sqrt(4); double result = Math.Sqrt(4); result=$(sqrt 4) $result = [Math]::Sqrt(4)
辞書 キーのリスト取得 d = {'a': 1, 'b': 2}
keys = list(d.keys())
let d = {'a': 1, 'b': 2};
let keys = Object.keys(d);
let d = vec![("a", 1), ("b", 2)];
let keys = d.iter().map(|(k, \_)| k).collect::<Vec<&str>>();
import Data.Map
let d = fromList [("a", 1), ("b", 2)]
let keys = keys d
std::map<std::string, int> d = {{"a", 1}, {"b", 2}};
std::vectorstd::string keys;
for (const auto& kvp : d) { keys.push_back(kvp.first); }
var d = new Dictionary<string, int> { { "a", 1 }, { "b", 2 } };
List<string> keys = d.Keys.ToList();
declare -A d=( ["a"]=1 ["b"]=2 )
keys=("${!d[@]}")
$d = @{"a"=1;"b"=2}
$keys = $d.Keys
辞書 値のリスト取得 d = {'a': 1, 'b': 2}
values = list(d.values())
let d = {'a': 1, 'b': 2};
let values = Object.values(d);
let d = vec![("a", 1), ("b", 2)];
let values = d.iter().map(|(\_, v)| v).collect::<Vec<&i32>>();
import Data.Map
let d = fromList [("a", 1), ("b", 2)]
let values = elems d
std::map<std::string, int> d = {{"a", 1}, {"b", 2}};
std::vector<int> values;
for (const auto& kvp : d) { values.push_back(kvp.second); }
var d = new Dictionary<string, int> { { "a", 1 }, { "b", 2 } };
List<int> values = d.Values.ToList();
declare -A d=( ["a"]=1 ["b"]=2 )
values=("${d[@]}")
$d = @{"a"=1;"b"=2}
$values = $d.Values
大分類 小分類 python JavaScript Rust Haskell C++ C# bash PowerShell
関数 クロージャ def outer(x):
  def inner(y):
  return x + y
  return inner
f = outer(10)
result = f(5)
function outer(x) {
  return function inner(y) {
  return x + y;
  };
}
let f = outer(10);
let result = f(5);
fn outer(x: i32) -> impl Fn(i32) -> i32 {
  move |y| x + y
}
let f = outer(10);
let result = f(5);
outer :: Int -> Int -> Int
outer x = \y -> x + y
f = outer 10
result = f 5
auto outer(int x) {
  return [x](int y) { return x + y; };
}
auto f = outer(10);
int result = f(5);
Func<int, int> Outer(int x) {
  return y => x + y;
}
var f = Outer(10);
int result = f(5);
outer() { x=$1; inner() { y=$1; echo $((x+y)); }; return 0; }
f=$(outer 10)
result=$(f 5)
function Outer($x) {
  return { param($y) $x + $y };
}
$f = Outer 10
$result = $f.Invoke(5)
関数 関数の戻り値 def add(x, y):
  return x + y
result = add(1, 2)
function add(x, y) {
  return x + y;
}
let result = add(1, 2);
fn add(x: i32, y: i32) -> i32 {
  x + y
}
let result = add(1, 2);
add :: Int -> Int -> Int
add x y = x + y
result = add 1 2
int add(int x, int y) {
  return x + y;
}
int result = add(1, 2);
int Add(int x, int y) {
  return x + y;
}
int result = Add(1, 2);
add() { return $(($1 + $2)); }
result=$(add 1 2)
function Add($x, $y) {
  return $x + $y;
}
$result = Add 1 2
数学 平方根の取得 import math
sqrt_val = math.sqrt(25)
const sqrt_val = Math.sqrt(25); use std::f64;
let sqrt_val = f64::sqrt(25.0);
sqrt_val = sqrt 25 double sqrt_val = std::sqrt(25); double sqrt_val = Math.Sqrt(25); sqrt_val=$(echo "scale=0;sqrt(25)" | bc) $sqrt_val = [Math]::Sqrt(25)
数学 絶対値の取得 abs_val = abs(-10) const abs_val = Math.abs(-10); let abs_val = i32::abs(-10); abs_val = abs (-10) int abs_val = std::abs(-10); int abs_val = Math.Abs(-10); abs_val=$(echo "scale=0;(-10)" | bc) $abs_val = [Math]::Abs(-10)
大分類 小分類 python JavaScript Rust Haskell C++ C# bash PowerShell
数学 三角関数の取得 import math
sin_val = math.sin(math.radians(30))
const sin_val = Math.sin(Math.PI / 6); use std::f64;
let sin_val = f64::sin(f64::consts::PI / 6.0);
sin_val = sin(pi / 6) double sin_val = std::sin(M_PI / 6); double sin_val = Math.Sin(Math.PI / 6); sin_val=$(echo "scale=2;sin(30 * 3.14159/180)" | bc -l) $sin_val = [Math]::Sin([Math]::PI / 6)
集合 集合の生成 my_set = {1, 2, 3} const mySet = new Set([1, 2, 3]); use std::collections::HashSet;
let my_set: HashSet<i32> = [1, 2, 3].iter().cloned().collect();
mySet = Data.Set.fromList [1, 2, 3] std::set<int> my_set = {1, 2, 3}; HashSet<int> mySet = new HashSet<int>(){1, 2, 3}; my_set=$(echo "1 2 3" | tr ' ' '\n' | sort -u) $mySet = [1, 2, 3] -as [System.Collections.Generic.HashSet[int]]
集合 要素の追加 my_set.add(4) mySet.add(4); my_set.insert(4); mySet = Data.Set.insert 4 mySet my_set.insert(4); mySet.Add(4); my_set=$(echo "$my_set"; echo "4") | sort -u $mySet.Add(4)
集合 要素の削除 my_set.remove(3) mySet.delete(3); my_set.remove(&3); mySet = Data.Set.delete 3 mySet my_set.erase(3); mySet.Remove(3); my_set=$(echo "$my_set" | grep -v '^3$') $mySet.Remove(3)
大分類 小分類 python JavaScript Rust Haskell C++ C# bash PowerShell
集合 長さ取得 len(my_set) mySet.size; my_set.len(); Data.Set.size mySet my_set.size(); mySet.Count; my_set_count=$(echo "$my_set" | wc -l) $mySet.Count
集合 集合の交差 set1 = {1, 2, 3}
set2 = {2, 3, 4}
intersection = set1.intersection(set2)
const set1 = new Set([1, 2, 3]);
const set2 = new Set([2, 3, 4]);
const intersection = new Set([...set1].filter(x => set2.has(x)));
use std::collections::HashSet;
let set1: HashSet<> = [1, 2, 3].iter().cloned().collect();
let set2: HashSet<> = [2, 3, 4].iter().cloned().collect();
let intersection: HashSet<> = set1.intersection(&set2).cloned().collect();
import qualified Data.Set as Set
set1 = Set.fromList [1, 2, 3]
set2 = Set.fromList [2, 3, 4]
intersection = Set.intersection set1 set2
std::set<int> set1{1, 2, 3};
std::set<int> set2{2, 3, 4};
std::set<int> intersection;
std::set_intersection(set1.begin(), set1.end(), set2.begin(), set2.end(), std::inserter(intersection, intersection.begin()));
HashSet<int> set1 = new HashSet<int> {1, 2, 3};
HashSet<int> set2 = new HashSet<int> {2, 3, 4};
set1.IntersectWith(set2);
set1=(1 2 3)
set2=(2 3 4)
intersection=($(comm -12 <(echo "${set1[@]}" | tr ' ' '\n' | sort) <(echo "${set2[@]}" | tr ' ' '\n' | sort)))
$set1 = @('1','2','3')
$set2 = @('2','3','4')
$intersection = $set1 | ? { $set2 -contains $ }
集合 集合の和集合 set1 = {1, 2, 3}
set2 = {3, 4, 5}
union_set = set1.union(set2)
const set1 = new Set([1, 2, 3]);
const set2 = new Set([3, 4, 5]);
const union_set = new Set([...set1, ...set2]);
use std::collections::HashSet;
let set1: HashSet<> = [1, 2, 3].iter().cloned().collect();
let set2: HashSet<> = [3, 4, 5].iter().cloned().collect();
let union_set: HashSet<_> = set1.union(&set2).cloned().collect();
import Data.Set
let set1 = fromList [1, 2, 3]
let set2 = fromList [3, 4, 5]
let union_set = set1 union set2
std::unordered_set<int> set1 = {1, 2, 3};
std::unordered_set<int> set2 = {3, 4, 5};
std::unordered_set<int> union_set;
std::set_union(set1.begin(), set1.end(), set2.begin(), set2.end(), std::inserter(union_set, union_set.begin()));
HashSet<int> set1 = new HashSet<int> {1, 2, 3};
HashSet<int> set2 = new HashSet<int> {3, 4, 5};
set1.UnionWith(set2);
set1=(1 2 3)
set2=(3 4 5)
union_set=($(echo "${set1[@]}" "${set2[@]}" | tr ' ' '\n' | sort -u | tr '\n' ' '))
$set1 = @(1, 2, 3)
$set2 = @(3, 4, 5)
$union_set = $set1 + $set2 | Sort-Object -Unique
集合 集合の差集合 set1 = {1, 2, 3}
set2 = {2, 3, 4}
difference = set1.difference(set2)
const set1 = new Set([1, 2, 3]);
const set2 = new Set([2, 3, 4]);
const difference = new Set([...set1].filter(x => !set2.has(x)));
use std::collections::HashSet;
let set1: HashSet<i32> = [1, 2, 3].iter().cloned().collect();
let set2: HashSet<i32> = [2, 3, 4].iter().cloned().collect();
let difference: HashSet<i32> = set1.difference(&set2).cloned().collect();
import Data.Set as Set
set1 = Set.fromList [1, 2, 3]
set2 = Set.fromList [2, 3, 4]
difference = Set.difference set1 set2
std::set<int> set1{1, 2, 3};
std::set<int> set2{2, 3, 4};
std::set<int> difference;
std::set_difference(set1.begin(), set1.end(), set2.begin(), set2.end(), std::inserter(difference, difference.begin()));
HashSet<int> set1 = new HashSet<int> { 1, 2, 3 };
HashSet<int> set2 = new HashSet<int> { 2, 3, 4 };
HashSet<int> difference = new HashSet<int>(set1);
difference.ExceptWith(set2);
set1="1 2 3"
set2="2 3 4"
difference=$(comm -23 <(echo "$set1" | tr ' ' '\n' | sort) <(echo "$set2" | tr ' ' '\n' | sort) | tr '\n' ' ')
$set1 = @(1, 2, 3)
$set2 = @(2, 3, 4)
$difference = $set1 | Where-Object { -not ($set2 -contains $_) }
集合 集合の部分集合判定 A = {1, 2, 3}
B = {1, 2}
is_subset = B.issubset(A)
const A = new Set([1, 2, 3]);
const B = new Set([1, 2]);
const is_subset = [...B].every(x => A.has(x));
use std::collections::HashSet;
let A: HashSet<i32> = [1, 2, 3].iter().cloned().collect();
let B: HashSet<i32> = [1, 2].iter().cloned().collect();
let is_subset = B.is_subset(&A);
import Data.Set (isSubsetOf, fromList)
let A = fromList [1, 2, 3]
let B = fromList [1, 2]
let is_subset = B isSubsetOf A
std::set<int> A{1, 2, 3};
std::set<int> B{1, 2};
bool is_subset = std::includes(A.begin(), A.end(), B.begin(), B.end());
HashSet<int> A = new HashSet<int>(){1, 2, 3};
HashSet<int> B = new HashSet<int>(){1, 2};
bool is_subset = B.IsSubsetOf(A);
A="1 2 3"
B="1 2"
is_subset=true
for e in $B; do if ! [[ $A =~ $e ]]; then is_subset=false; break; fi; done
$A = @{1, 2, 3}
$B = @{1, 2}
$is_subset = $B.IsSubsetOf($A)

Discussion