プログラミング言語の比較 > その他

ローカル変数の名前を全て出力する

Ruby

  1. local_variables.each {|v| puts v }

Python

  1. k = None # 事前に定義しておかないと例外が起きる
  2. for k in locals().keys():
  3. print(k)

指定された処理を指定された回数だけ繰り返し実行する関数

Java

引数なし
  1. public static void times(int n, Runnable action) {
  2. for (int i = 0; i < n; i++) {
  3. action.run();
  4. }
  5. }
  1. times(3, () -> System.out.println("Done."));
引数あり
  1. // import java.util.function.IntConsumer;
  2. // import java.util.stream.IntStream;
  3. public static void times(int n, IntConsumer action) {
  4. IntStream.iterate(0, i -> i + 1).limit(n).forEach(action);
  5. }
  1. times(3, System.out::println);

Groovy

  1. def times(n, action) {
  2. (1..n).each { action it }
  3. }
  1. times(3) { println 'Done.' }
  1. times(3) { println it }
  1. times(3, this.&println)

Kotlin

引数なし
  1. fun times(n: Int, action: () -> Unit) = (1..n).forEach { action() }
  1. times(3) { println("Done.") }
引数あり
  1. fun times(n: Int, action: (Int) -> Unit) = (1..n).forEach(action)
  1. times(3, ::println)
  1. times(3) { println(it) }

Scala

引数なし
  1. def times(n: Int)(action: => Unit) = (1 to n).foreach(_ => action)
  1. times(3)(println("Done."))
  1. times(3) { println("Done.") }
引数あり
  1. def times(n: Int)(action: => (Int) => Unit) = (1 to n).foreach(action)
  1. times(3)(println)
  1. times(3) { println _ }

Erlang

引数あり
  1. times(N, Action) ->
  2. case N of
  3. 0 ->
  4. void;
  5. N when N > 0 ->
  6. Action(N),
  7. times(N - 1, Action)
  8. end.
  1. times(3, fun(N) -> io:format("~b~n", [N]) end).

Haskell

引数なし
  1. times n action | n > 0 = do
  2. action
  3. times (n - 1) action
  4. times _ _ = return ()
  1. times 3 (putStrLn "Done.")
引数あり
  1. times n action | n > 0 = do
  2. action n
  3. times (n - 1) action
  4. times _ _ = return ()
  1. times 3 print

F#

引数なし
  1. let times n action = for i = 1 to n do action()
  1. times 3 (fun () -> printfn "Done.")
  1. times 3 <| fun () -> printfn "Done."
引数あり
  1. let times n action = for i = 1 to n do action i
  1. times 3 (printfn "%d")
  1. times 3 <| printfn "%d"

C#

引数なし

  1. public static void Times(int n, Action action) {
  2. for (int i = 1; i <= n; i++) action();
  3. }
  1. Times(3, () => Console.WriteLine("Done."));

引数あり

  1. public static void Times(int n, Action<int> action) {
  2. for (int i = 1; i <= n; i++) action(i);
  3. }
  1. Times(3, Console.WriteLine);

Go

引数なし
  1. func times(n int, action func()) {
  2. for i := 0; i < n; i++ { action() }
  3. }
  1. times(3, func() { fmt.Printf("Done.\n") })
引数あり
  1. func times(n int, action func(int)) {
  2. for i := 0; i < n; i++ { action(i) }
  3. }
  1. times(3, func(n int) { fmt.Printf("%d\n", n) })

Rust

引数なし
  1. // use std::ops::*;
  2. pub fn times<F>(n: i32, f: F) where F: Fn() -> () {
  3. let range = Range { start: 0, end: n };
  4. for i in range {
  5. f()
  6. }
  7. }
  1. times(3, || { println!("Done.") });
引数あり
  1. // use std::ops::*;
  2. pub fn times<F>(n: i32, f: F) where F: Fn(i32) -> () {
  3. let range = Range { start: 0, end: n };
  4. for i in range {
  5. f(i)
  6. }
  7. }
  1. times(3, |i| { println!("{i}") });

Dart

引数あり
  1. void times(int n, void action(int i)) {
  2. for (var i = 0; i < n; i++) {
  3. action(i);
  4. }
  5. }
  1. times(3, print);

TypeScript

  1. function times(n: number, action: (i: number) => void) {
  2. for (let i = 0; i < n; i++) {
  3. action(i);
  4. }
  5. }
  1. times(3, () => console.log('Done'));
  1. times(3, console.log);

JavaScript

  1. function times(n, action) {
  2. for (let i = 0; i < n; i++) {
  3. action(i);
  4. }
  5. }
  1. times(3, () => console.log('Done'));
  1. times(3, console.log);

CoffeeScript

  1. times = (n, action) ->
  2. action i for i in [0...n]
  3. return # この return を省いた場合、余分な配列が生成されてそれが戻り値になる
  1. times 3, (-> console.log 'Done')
  1. times 3, console.log

Ruby

  1. def times(n, &block)
  2. (1..n).each {|i| block.call i }
  3. end
  1. times(3) { puts 'Done.' }
  1. times(3) {|i| puts i }

Python

引数なし
  1. def times(n, action):
  2. for i in range(0, n):
  3. action()
  1. times(3, lambda: print('Done.'))
引数あり
  1. def times(n, action):
  2. for i in range(0, n):
  3. action(i)
  1. times(3, print)

PHP

  1. function times($n, $action) {
  2. for ($i = 0; $i < $n; $i++) {
  3. $action($i);
  4. }
  5. }
  1. times(3, function() { echo "Done.\n"; });
  1. times(3, function($n) { echo "$n\n"; });

Perl

普通の関数
  1. sub _times ($&) { # times は組み込み関数
  2. my ($n, $action) = @_;
  3. $action->($_) for 1..$n;
  4. }
  1. _times 3, sub { print "Done.\n" };
  1. _times 3, sub { print "$_\n" };
制御構造風
  1. sub _times (&$) { # times は組み込み関数
  2. my ($action, $n) = @_;
  3. $action->($_) for 1..$n;
  4. }
  1. _times { print "Done.\n" } 3;
  1. _times { print "$_\n" } 3;

外部のプログラムを実行し、標準出力への出力内容と終了コードを取得する

Java

  1. // import java.io.*;
  2. Process process = new ProcessBuilder("java", "-help")
  3. .redirectErrorStream(true)
  4. .start();
  5. StringWriter sw = new StringWriter();
  6. try (InputStream stdout = process.getInputStream()) {
  7. new InputStreamReader(stdout, "ASCII").transferTo(sw);
  8. }
  9. int exitCode = process.waitFor();
  10. String output = sw.toString();
Commons Exec を使った場合
  1. // import java.io.ByteArrayOutputStream;
  2. // import org.apache.commons.exec.*;
  3. DefaultExecutor executor = new DefaultExecutor();
  4. ByteArrayOutputStream stream = new ByteArrayOutputStream();
  5. executor.setStreamHandler(new PumpStreamHandler(stream));
  6. CommandLine commandLine = new CommandLine("java");
  7. commandLine.addArgument("-help");
  8. int exitCode = executor.execute(commandLine);
  9. String output = stream.toString("ASCII");

Groovy

  1. def process = new ProcessBuilder('java', '-help')
  2. .redirectErrorStream(true)
  3. .start()
  4. def output = process.in.withReader('ASCII') { it.text }
  5. def exitCode = process.waitFor()

Kotlin

  1. val process = ProcessBuilder("java", "-help")
  2. .redirectErrorStream(true)
  3. .start()
  4. val output = process.getInputStream().use { it.reader().readText() }
  5. val exitCode = process.waitFor()

Scala

  1. // import java.io.ByteArrayOutputStream
  2. // import scala.sys.process.Process
  3. val stream = new ByteArrayOutputStream
  4. val builder = Process(List("java", "-help")) #> stream
  5. val exitCode = builder.run.exitValue
  6. val output = stream.toString("ASCII")
  1. // import java.io.InputStream
  2. // import scala.io.Source
  3. // import scala.sys.process._
  4. val builder = Process(List("java", "-help"))
  5. val output = new StringBuilder
  6. def appendLines(in: InputStream) = Source.fromInputStream(in, "ASCII").foreach(output.append)
  7. val io = new ProcessIO(_.close, appendLines, appendLines)
  8. val exitCode = builder.run(io).exitValue
終了コードが不要な場合
  1. // import scala.sys.process.Process
  2. val separator = System.getProperty("line.separator")
  3. val output = Process(List("java", "-help")).lines mkString separator

Erlang

  1. wait(Port, L) ->
  2. receive
  3. {Port, {data, Data}} -> wait(Port, [Data|L]);
  4. {Port, {exit_status, ExitCode}} -> {ExitCode, lists:append(lists:reverse(L))}
  5. end.
  1. Port = open_port({spawn, "java -help"}, [exit_status]),
  2. {ExitCode, Output} = wait(Port, []).

Haskell

  1. -- import System.Process
  2. (exitCode, output, error) <- readProcessWithExitCode "java" ["-help"] ""
  1. -- import Control.Exception
  2. -- import IO
  3. -- import System.Process
  4. (stdin, stdout, stderr, pid) <- runInteractiveProcess "java" ["-help"] Nothing Nothing
  5. hClose stdin
  6. finally
  7. (do output <- hGetContents stdout
  8. error <- hGetContents stderr
  9. exitCode <- waitForProcess pid)
  10. (do hClose stdout
  11. hClose stderr)
  1. -- import Control.Exception
  2. -- import IO
  3. -- import System.Process
  4. (_, Just stdout, Just stderr, pid) <-
  5. createProcess (proc "java" ["-help"]) { std_out = CreatePipe, std_err = CreatePipe }
  6. finally
  7. (do output <- hGetContents stdout
  8. error <- hGetContents stderr
  9. exitCode <- waitForProcess pid)
  10. (do hClose stdout
  11. hClose stderr)

PowerShell

  1. $output = java -help
  2. $exitCode = $LastExitCode

F#

  1. // open System.Diagnostics
  2. // open System.Text
  3. let p = new ProcessStartInfo("java", "-help",
  4. RedirectStandardOutput = true,
  5. StandardOutputEncoding = Encoding.ASCII,
  6. UseShellExecute = false
  7. ) |> Process.Start
  8. let output = p.StandardOutput.ReadToEnd
  9. p.WaitForExit()
  10. let exitCode = p.ExitCode
  1. // open System.Diagnostics
  2. // open System.IO
  3. // open System.Text
  4. let p = new ProcessStartInfo("java", "-help",
  5. RedirectStandardOutput = true,
  6. StandardOutputEncoding = Encoding.ASCII,
  7. UseShellExecute = false
  8. ) |> Process.Start
  9. let sw = new StringWriter()
  10. p.OutputDataReceived.AddHandler <| DataReceivedEventHandler(fun _ args -> sw.WriteLine args.Data)
  11. p.BeginOutputReadLine()
  12. p.WaitForExit()
  13. let output = string sw
  14. let exitCode = p.ExitCode

C#

  1. // using System.Diagnostics;
  2. var p = Process.Start(new ProcessStartInfo("java", "-help") {
  3. RedirectStandardOutput = true,
  4. StandardOutputEncoding = Encoding.ASCII,
  5. UseShellExecute = false
  6. });
  7. var output = p.StandardOutput.ReadToEnd();
  8. p.WaitForExit();
  9. var exitCode = p.ExitCode;
  1. // using System.Diagnostics;
  2. // using System.IO;
  3. var p = Process.Start(new ProcessStartInfo("java", "-help") {
  4. RedirectStandardOutput = true,
  5. StandardOutputEncoding = Encoding.ASCII,
  6. UseShellExecute = false
  7. });
  8. var sw = new StringWriter();
  9. p.OutputDataReceived += (sender, args) => sw.WriteLine(args.Data);
  10. p.BeginOutputReadLine();
  11. p.WaitForExit();
  12. var output = sw.ToString();
  13. var exitCode = p.ExitCode;

Go

  1. // import "os"
  2. pipeReader, pipeWriter, err := os.Pipe()
  3. if err != nil { return err }
  4. defer pipeReader.Close()
  5. defer pipeWriter.Close()
  6. fd := []*os.File{nil, pipeWriter, pipeWriter}
  7. pid, err := os.ForkExec("java", []string{"", "-help"}, []string{}, ".", fd)
  8. if err != nil { return err }
  9. pipeWriter.Close()
  10. var output string
  11. var buf [1024]byte
  12. for {
  13. n, err := pipeReader.Read(buf[:])
  14. if err == os.EOF { break }
  15. if err != nil { return err }
  16. output += string(buf[:n])
  17. }
  18. waitmsg, err := os.Wait(pid, os.WNOHANG)
  19. if err != nil { return err }
  20. exitCode := waitmsg.ExitStatus()

Rust

  1. // use std::process;
  2. let output = process::Command::new("java").arg("-help").output().unwrap();
  3. let stdout = String::from_utf8(output.stdout).unwrap();
  4. let exit_code = output.status.code().unwrap();

TypeScript

Node.js の場合
  1. // import * as child_process from 'child_process';
  2. child_process.exec('java -help', (error, stdout, stderr) => {
  3. let exitCode = error ? error.code : 0;
  4. let output = stdout + stderr;
  5. ...
  6. });

JavaScript

Node.js の場合
  1. // const child_process = require('child_process');
  2. child_process.exec('java -help', (error, stdout, stderr) => {
  3. let exitCode = error ? error.code : 0;
  4. let output = stdout + stderr;
  5. ...
  6. });

CoffeeScript

Node.js の場合
  1. # child_process = require 'child_process'
  2. child_process.exec 'java -help', (error, stdout, stderr) ->
  3. exitCode = if error then error.code else 0
  4. output = stdout + stderr
  5. ...

Ruby

  1. output = `java -help`
  2. exit_code = $?.exitstatus
  1. pipe_in, pipe_out = IO.pipe
  2. pid = spawn({}, 'java', '-help', out: pipe_out, err: pipe_out)
  3. pipe_out.close
  4. output = pipe_in.readline nil
  5. Process.waitpid pid
  6. exit_code = $?.exitstatus
終了コードが不要の場合
  1. output = open('| java -help') {|io| io.readline nil }
  1. output = IO.popen('java -help') {|io| io.readline nil }

Python

  1. # import codecs
  2. # import subprocess
  3. reader_class = codecs.getreader('ascii')
  4. process = subprocess.Popen('java -help', stdout = subprocess.PIPE, stderr = subprocess.STDOUT)
  5. output = reader_class(process.stdout).read()
  6. exit_code = process.wait()
  1. # import subprocess
  2. process = subprocess.Popen('java -help', stdout = subprocess.PIPE, stderr = subprocess.STDOUT)
  3. (output_bytes, error_bytes) = process.communicate()
  4. output = output_bytes.decode('ascii')
  5. exit_code = process.returncode

PHP

  1. exec('java -help', $outputLines, $exitCode);
  2. $output = implode("\n", $outputLines);
終了コードが不要の場合
  1. $output = `java -help`;
  1. $output = shell_exec('java -help');
  1. $pipe = popen('java -help', 'r');
  2. while (($line = fgets($pipe)) !== FALSE) {
  3. $output .= $line;
  4. }
  5. pclose($pipe);

Perl

(Windows 上では動作しない)
  1. my $pid = open(PIPE, '-|', 'java', '-help') or die "Cannot open pipe; $!";
  2. my $output = join '', <PIPE>;
  3. waitpid $pid, 0;
  4. my $exit_code = $?;
  1. pipe PIPE_IN, PIPE_OUT or die $!;
  2. my $pid = fork;
  3. defined($pid) or die "Cannot fork; $!";
  4. unless ($pid) {
  5. # 子プロセスでの処理
  6. close PIPE_IN;
  7. open STDOUT, '>&PIPE_OUT' or die $!;
  8. exec 'java', '-help';
  9. die "Cannot exec java; $!";
  10. }
  11. # 親プロセスでの処理
  12. close PIPE_OUT;
  13. my $output = join '', <PIPE_IN>;
  14. waitpid $pid, 0;
  15. my $exit_code = $?;
終了コードが不要の場合
(こちらは Windows 上でも動作する)
  1. my $output = `java -help`;
  1. open my $pipe, 'java -help |';
  2. my $output = join '', <$pipe>;

外部のプログラムの標準入力にファイルの内容を渡し、標準出力への出力内容を別のファイルに書き込む

Java

  1. // import java.io.*;
  2. Process process = new ProcessBuilder("sort")
  3. .redirectInput(new File("in.txt"))
  4. .redirectOutput(new File("out.txt"))
  5. .start();
  6. int exitCode = process.waitFor();
Commons Exec を使った場合
  1. // import java.io.*;
  2. // import java.nio.file.*;
  3. // import org.apache.commons.exec.*;
  4. try (InputStream inStream = Files.newInputStream(Path.of("in.txt"));
  5. OutputStream outStream = Files.newOutputStream(Path.of("out.txt"))) {
  6. DefaultExecutor executor = new DefaultExecutor();
  7. executor.setStreamHandler(new PumpStreamHandler(outStream, outStream, inStream));
  8. CommandLine commandLine = new CommandLine("sort");
  9. int exitCode = executor.execute(commandLine);
  10. }

Groovy

  1. def process = new ProcessBuilder('sort')
  2. .redirectInput(new File('in.txt'))
  3. .redirectOutput(new File('out.txt'))
  4. .start()
  5. def exitCode = process.waitFor()

Kotlin

  1. // import java.io.File
  2. val process = ProcessBuilder("sort")
  3. .redirectInput(File("in.txt"))
  4. .redirectOutput(File("out.txt"))
  5. .start()
  6. val exitCode = process.waitFor()

Scala

  1. // import java.io.File
  2. // import scala.sys.process.Process
  3. val builder = Process("sort") #< new File("in.txt") #> new File("out.txt")
  4. val exitCode = builder.run.exitValue

Erlang

  1. os:cmd("sort < in.txt > out.txt").

Haskell

  1. -- import System.Process
  2. contents <- readFile "in.txt"
  3. (exitCode, output, error) <- readProcessWithExitCode "sort" [] contents
  4. writeFile "out.txt" output
  1. -- import Control.Exception
  2. -- import IO
  3. -- import System.Process
  4. (stdin, stdout, stderr, pid) <- runInteractiveProcess "sort" [] Nothing Nothing
  5. finally
  6. (do finally
  7. (readFile "in.txt" >>= hPutStr stdin)
  8. (hClose stdin)
  9. output <- hGetContents stdout
  10. exitCode <- waitForProcess pid
  11. writeFile "out.txt" output)
  12. (do hClose stdout
  13. hClose stderr)
  1. -- import Control.Exception
  2. -- import IO
  3. -- import System.Process
  4. (Just stdin, Just stdout, Just stderr, pid) <-
  5. createProcess (proc "sort" []) { std_in = CreatePipe, std_out = CreatePipe, std_err = CreatePipe }
  6. finally
  7. (do finally
  8. (readFile "in.txt" >>= hPutStr stdin)
  9. (hClose stdin)
  10. output <- hGetContents stdout
  11. exitCode <- waitForProcess pid
  12. writeFile "out.txt" output)
  13. (do hClose stdout
  14. hClose stderr)

PowerShell

  1. Get-Content in.txt | sort | Set-Content out.txt
  2. $exitCode = $LastExitCode

F#

  1. // open System.Diagnostics
  2. // open System.IO
  3. // open System.Text
  4. let p = new ProcessStartInfo("sort",
  5. RedirectStandardInput = true,
  6. RedirectStandardOutput = true,
  7. StandardOutputEncoding = Encoding.ASCII,
  8. UseShellExecute = false
  9. ) |> Process.Start
  10. use sr = new StreamReader "in.txt"
  11. use sw = new StreamWriter "out.txt"
  12. p.OutputDataReceived.AddHandler <| DataReceivedEventHandler(fun _ args -> sw.WriteLine args.Data)
  13. p.BeginOutputReadLine()
  14. sr.ReadToEnd() |> p.StandardInput.Write
  15. p.StandardInput.Close()
  16. p.WaitForExit()
  17. let exitCode = p.ExitCode

C#

  1. // using System.Diagnostics;
  2. // using System.IO;
  3. var p = Process.Start(new ProcessStartInfo("sort") {
  4. RedirectStandardInput = true,
  5. RedirectStandardOutput = true,
  6. StandardOutputEncoding = Encoding.ASCII,
  7. UseShellExecute = false
  8. });
  9. using (var sr = new StreamReader("in.txt")) {
  10. using (var sw = new StreamWriter("out.txt")) {
  11. p.OutputDataReceived += (sender, args) => sw.WriteLine(args.Data);
  12. p.BeginOutputReadLine();
  13. p.StandardInput.Write(sr.ReadToEnd());
  14. p.StandardInput.Close();
  15. p.WaitForExit();
  16. var exitCode = p.ExitCode;
  17. }
  18. }

Go

  1. // import "os"
  2. inFile, err := os.Open("in.txt", os.O_RDONLY, 0)
  3. if err != nil { return err }
  4. defer inFile.Close()
  5. outFile, err := os.Open("out.txt", os.O_WRONLY | os.O_CREAT | os.O_TRUNC, 0644)
  6. if err != nil { return err }
  7. defer outFile.Close()
  8. fd := []*os.File{inFile, outFile, nil}
  9. pid, err := os.ForkExec("/bin/sort", []string{""}, []string{}, ".", fd)
  10. if err != nil { return err }
  11. waitmsg, err := os.Wait(pid, os.WNOHANG)
  12. if err != nil { return err }
  13. exitCode := waitmsg.ExitStatus()

Rust

  1. // use std::fs;
  2. // use std::process;
  3. let in_file = fs::File::open("in.txt").unwrap();
  4. let out_file = fs::File::create("out.txt").unwrap();
  5. let status = process::Command::new("sort").stdin(in_file).stdout(out_file).status().unwrap();
  6. let exit_code = status.code().unwrap();

TypeScript

Node.js の場合
  1. // import * as child_process from 'child_process';
  2. child_process.exec('sort < in.txt > out.txt', (error, stdout, stderr) => {
  3. let exitCode = error ? error.code : 0;
  4. ...
  5. });
  1. // import * as child_process from 'child_process';
  2. // import * as fs from 'fs';
  3. let inFile = fs.openSync('in.txt', 'r');
  4. try {
  5. let outFile = fs.openSync('out.txt', 'w');
  6. try {
  7. let child = child_process.spawn('sort', [], { stdio: [inFile, outFile, outFile] });
  8. child.on('exit', (code, signal) => {
  9. fs.closeSync(inFile);
  10. fs.closeSync(outFile);
  11. let exitCode = code;
  12. ...
  13. });
  14. } catch (e) {
  15. fs.closeSync(outFile);
  16. throw e;
  17. }
  18. } catch (e) {
  19. fs.closeSync(inFile);
  20. throw e;
  21. }

JavaScript

Node.js の場合
  1. // const child_process = require('child_process');
  2. child_process.exec('sort < in.txt > out.txt', (error, stdout, stderr) => {
  3. let exitCode = error ? error.code : 0;
  4. ...
  5. });
  1. // const child_process = require('child_process');
  2. // const fs = require('fs');
  3. let inFile = fs.openSync('in.txt', 'r');
  4. try {
  5. let outFile = fs.openSync('out.txt', 'w');
  6. try {
  7. let child = child_process.spawn('sort', [], { stdio: [inFile, outFile, outFile] });
  8. child.on('exit', (code, signal) => {
  9. fs.closeSync(inFile);
  10. fs.closeSync(outFile);
  11. let exitCode = code;
  12. ...
  13. });
  14. } catch (e) {
  15. fs.closeSync(outFile);
  16. throw e;
  17. }
  18. } catch (e) {
  19. fs.closeSync(inFile);
  20. throw e;
  21. }

CoffeeScript

Node.js の場合
  1. # child_process = require 'child_process'
  2. child_process.exec 'sort < in.txt > out.txt', (error, stdout, stderr) ->
  3. exitCode = if error then error.code else 0
  4. ...
  1. # child_process = require 'child_process'
  2. # fs = require 'fs'
  3. inFile = fs.openSync 'in.txt', 'r'
  4. try
  5. outFile = fs.openSync 'out.txt', 'w'
  6. try
  7. child = child_process.spawn 'sort', [], stdio: [inFile, outFile, outFile]
  8. child.on 'exit', (code, signal) ->
  9. fs.closeSync inFile
  10. fs.closeSync outFile
  11. exitCode = code
  12. ...
  13. catch e
  14. fs.closeSync outFile
  15. throw e
  16. catch e
  17. fs.closeSync inFile
  18. throw e

Ruby

  1. `sort < in.txt > out.txt`
  2. exit_code = $?.exitstatus
  1. open 'in.txt', 'r' do |in_file|
  2. open 'out.txt', 'w' do |out_file|
  3. pid = spawn({}, 'sort', in: in_file, out: out_file)
  4. Process.waitpid pid
  5. exit_code = $?.exitstatus
  6. end
  7. end

Python

  1. # import subprocess
  2. with open('in.txt', 'r') as in_file:
  3. with open('out.txt', 'w') as out_file:
  4. process = subprocess.Popen('sort', stdin = in_file, stdout = out_file)
  5. exit_code = process.wait()

PHP

  1. exec('sort < in.txt > out.txt', $_, $exitCode);

Perl

(Windows 上では動作しない)
  1. my $pid = fork;
  2. defined($pid) or die "Cannot fork; $!";
  3. unless ($pid) {
  4. # 子プロセスでの処理
  5. open STDIN, 'in.txt' or die $!;
  6. open STDOUT, '>out.txt' or die $!;
  7. exec 'sort';
  8. die "Cannot exec sort; $!";
  9. }
  10. # 親プロセスでの処理
  11. waitpid $pid, 0;
  12. my $exit_code = $?;
終了コードが不要な場合
(こちらは Windows 上でも動作する)
  1. `sort < in.txt > out.txt`;

ユニットテスト

Java

JUnit 5を使った場合
  1. // import static org.junit.jupiter.api.Assertions.*;
  2. assertEquals("期待値", str);
  3. assertAll("str",
  4. () -> assertNotNull(str),
  5. () -> assertNotEquals("", str));
JUnit 4.4以降を使った場合
  1. // import static org.hamcrest.CoreMatchers.*;
  2. // import static org.junit.Assert.assertThat;
  3. assertThat(str, is("期待値"));
  4. assertThat(str, allOf(
  5. is(not(nullValue())),
  6. is(not(""))
  7. ));

Groovy

JUnit を使った場合
  1. // groovy.util.GroovyTestCase クラスのサブクラス内で
  2. assertEquals str, '期待値'
  3. assertTrue str != null && str != ''
JUnit 4.4以降を使った場合
  1. // import static org.hamcrest.CoreMatchers.*
  2. // import static org.junit.Assert.assertThat
  3. assertThat str, is('期待値')
  4. assertThat str, allOf(
  5. is(not(nullValue())),
  6. is(not(''))
  7. )

Scala

ScalaTest を使った場合
  1. // org.scalatest.matchers.ShouldMatchers trait を継承したオブジェクト内で
  2. str should be ("期待値")
  3. str should (not be null and not be (""))
  1. // org.scalatest.matchers.ShouldMatchers trait を継承したオブジェクト内で
  2. str should be === "期待値"
  3. str should (not be === (null) and not be === (""))
  1. // org.scalatest.matchers.ShouldMatchers trait を継承したオブジェクト内で
  2. str should equal ("期待値")
  3. str should (not equal (null) and not equal (""))
specs2 を使った場合
  1. // org.specs2.Specification trait または org.specs2.mutable.Specification trait を継承したオブジェクト内で
  2. str must_== "期待値"
  3. str must_!= null and (str must_!= "")
  1. // org.specs2.Specification trait または org.specs2.mutable.Specification trait を継承したオブジェクト内で
  2. str must be ("期待値")
  3. str must not be null and not be ""
  1. // org.specs2.Specification trait または org.specs2.mutable.Specification trait を継承したオブジェクト内で
  2. str must be equalTo "期待値"
  3. str must not be equalTo (null) and not be equalTo ("")
  1. // org.specs2.Specification trait または org.specs2.mutable.Specification trait を継承したオブジェクト内で
  2. str === "期待値"
  3. (str !== null) and (str !== "")

Erlang

EUnit を使った場合
  1. ?_assertEqual("期待値", Str),
  2. ?_assert(Str =/= "").

Haskell

Cabal の HUnit を使った場合
  1. -- import Test.HUnit
  2. assertEqual "期待値と等しい" "期待値" str
  3. assertBool "空でない" (str /= "")

F#

NUnit を使った場合
  1. // open NUnit.Framework
  2. Assert.That(str, Is.EqualTo "期待値")
  3. Assert.That(str, Is.Not.Null.And.Not.EqualTo "")
NUnit と FsUnit を使った場合
  1. // open NUnit.Framework
  2. // open FsUnit
  3. str |> should equal "期待値"
  4. str |> should not' (be NullOrEmptyString)

C#

NUnit を使った場合
  1. // using NUnit.Framework;
  2. Assert.That(str, Is.EqualTo("期待値"));
  3. Assert.That(str, Is.Not.Null & Is.Not.EqualTo(""));

Go

  1. // import "testing"
  2. // t := new(testing.T)
  3. if str != "期待値" {
  4. t.Errorf("str: %s", str)
  5. }

Rust

  1. assert_eq!(str, "期待値");
  2. assert!(str != "");

TypeScript

Node.js の場合
  1. // import * as assert from 'assert';
  2. assert.equal(str, '期待値');
  3. assert(str !== null && str !== '');
Jasmine を使った場合
  1. expect(str).toEqual('期待値');
  2. expect(str !== null && str !== '').toBeTrue();

JavaScript

Node.js の場合
  1. // const assert = require('assert');
  2. assert.equal(str, '期待値');
  3. assert(str !== null && str !== '');
Jasmine を使った場合
  1. expect(str).toEqual('期待値');
  2. expect(str !== null && str !== '').toBeTrue();

CoffeeScript

Node.js の場合
  1. # assert = require 'assert'
  2. assert.equal str, '期待値'
  3. assert str != null && str != ''
Jasmine を使った場合
  1. expect(str).toEqual '期待値'
  2. expect(str != null && str != '').toBeTrue()

Ruby

Test::Unit を使った場合
  1. # require 'test/unit'
  2. # Test::Unit::TestCase クラスのサブクラス内で
  3. assert_equal('期待値', str)
  4. assert(! str.nil? && str != '')
RSpec を使った場合
  1. str.should == '期待値'
  2. str.should_not be_nil
  3. str.should_not == ''

Python

  1. # import unittest
  2. # unittest.TestCase クラスのサブクラス内で
  3. self.assertEqual(str, '期待値')
  4. self.assertTrue(str != None and str != '')

PHP

PHPUnit を使った場合
  1. // PHPUnit_Framework_TestCase クラスのサブクラス内で
  2. $this->assertEquals($str, '期待値');
  3. $this->assertTrue($str !== null && $str !== '');
  1. // PHPUnit_Framework_TestCase クラスのサブクラス内で
  2. $this->assertThat($str, $this->equalTo('期待値'));
  3. $this->assertThat($str, $this->logicalAnd(
  4. $this->logicalNot($this->isNull()),
  5. $this->logicalNot($this->equalTo(''))
  6. ));

Perl

CPAN の Test::More を使った場合
  1. # use Test::More;
  2. is $str, '期待値';
  3. ok defined($str) && $str ne '';

引数の部分適用

Groovy

クロージャに対して(curry というメソッドが用意されているが、正しくはカリー化ではなく部分適用)
  1. def power = { x, y -> x ** y }
  2. def powerOf2 = power.curry(2) // x に2を適用
  3. def sixteen = powerOf2(4)
メソッドに対して
  1. def power(x, y) { x ** y }
  2. def powerOf2 = this.&power.curry(2) // x に2を適用
  3. def sixteen = powerOf2(4)

Scala

クロージャに対して
  1. val power = (x: Double, y: Double) => Math.pow(x, y)
  2. val powerOf2 = power(2, _: Double) // x に2を適用
  3. val sixteen = powerOf2(4)
メソッドに対して
  1. val powerOf2 = Math.pow(2, _: Double) // 第1引数に2を適用
  2. val sixteen = powerOf2(4)

Erlang

  1. PowerOf2 = fun(Y) -> math:pow(2, Y) end,
  2. Sixteen = PowerOf2(4).

Haskell

  1. let power = (^) -- 二項演算子を関数化
  2. let powerOf2 = power 2 -- 引数を2つ取る power 関数の第1引数に2を適用
  3. -- もしくは let powerOf2 = (2 ^)
  4. let sixteen = powerOf2 4

F#

  1. let powerOf2 = pown 2 // 引数を2つ取る pown 関数の第1引数に2を適用
  2. let sixteen = powerOf2 4

C#

  1. Func<double, double> powerOf2 = y => Math.Pow(2, y); // 引数を2つ取る Pow メソッドの第1引数に2を適用
  2. var sixteen = powerOf2(4);

C++

Boost を使った場合
  1. #include <boost/bind.hpp>
  2. #include <math.h>
  3. boost::_bi::bind_t<
  4. double,
  5. double (*)(double, double),
  6. boost::_bi::list2<boost::_bi::value<double>, boost::arg<1> >
  7. > power_of_2 = boost::bind(power, 2.0, _1); // 引数を2つ取る power 関数の第1引数に2.0を適用
  8. double four = 4.0;
  9. double sixteen = power_of_2(four); // 数値リテラルは渡せない

Go

  1. powerOf2 := func(y float64) float64 { return math.Pow(2, y) }
  2. sixteen := powerOf2(4)

TypeScript

Underscore を使った場合
  1. // import * as _ from 'underscore';
  2. let powerOf2 = _.partial(Math.pow, 2);
  3. let sixteen = powerOf2(4);

JavaScript

Underscore を使った場合
  1. // const _ = require('underscore');
  2. let powerOf2 = _.partial(Math.pow, 2);
  3. let sixteen = powerOf2(4);

CoffeeScript

Underscore を使った場合
  1. # _ = require('underscore');
  2. powerOf2 = _.partial Math.pow, 2
  3. sixteen = powerOf2 4

Ruby

メソッドに対して
  1. def power(x, y)
  2. x ** y
  3. end
  4. power_of_2 = method(:power).to_proc.curry[2]
  5. sixteen = power_of_2[4]
ブロックに対して
  1. power = proc {|x, y| x ** y }
  2. power_of_2 = power.curry[2]
  3. sixteen = power_of_2[4]

Python

  1. # import functools
  2. powerOf2 = functools.partial(pow, 2) # 引数を2つ取る pow 関数の第1引数に2を適用
  3. sixteen = powerOf2(4)

PHP

  1. $powerOf2 = function($y) { return pow(2, $y); };
  2. $sixteen = $powerOf2(4);

Perl

  1. sub power {
  2. shift() ** shift();
  3. }
  4. my $power_of_2 = sub { power(2, shift) };
  5. my $sixteen = $power_of_2->(4);

引数の部分適用を行う関数

Scala

  1. // 引数が2つの場合
  2. def partial[T1, T2, TResult](func: => (T1, T2) => TResult)(arg1: T1) = func.curried(arg1)
クロージャに対して
  1. var power = (x: Double, y: Double) => Math.pow(x, y) // (Double, Double) => Double
  2. var powerOf2 = partial(power)(2) // (Double) => Double
  3. var sixteen = powerOf2(4) // 16.0
メソッドに対して
  1. var powerOf2 = partial(Math.pow _)(2) // (Double) => Double
  2. var sixteen = powerOf2(4) // 16.0

Erlang

  1. %% 引数が2つの場合
  2. partial(F, Arg1) ->
  3. fun(Arg2) -> F(Arg1, Arg2) end.
  1. PowerOf2 = partial(fun math:pow/2, 2),
  2. Sixteen = PowerOf2(4).

F#

  1. // 引数が2つの場合
  2. let partial (f : 'a -> 'b -> 'c) a = f a
  1. let powerOf2 = partial pown 2 // 右辺を「pown 2」としても同じ
  2. let sixteen = powerOf2 4

C#

  1. // 引数が2つの場合
  2. public static Func<T2, TResult> Partial<T1, T2, TResult>(this Func<T1, T2, TResult> func, T1 arg1) {
  3. return (arg2) => func(arg1, arg2);
  4. }
  1. var powerOf2 = Partial<double, double, double>(Math.Pow, 2); // Func<double, double>
  2. double sixteen = powerOf2(4); // 16.0
  1. Func<double, double, double> power = Math.Pow;
  2. var powerOf2 = power.Partial(2); // Func<double, double>
  3. double sixteen = powerOf2(4); // 16.0

Go

  1. // 引数が2つで型が float64 の場合
  2. func Partial(f func(float64, float64) float64, arg1 float64) func(float64) float64 {
  3. return func(arg2 float64) float64 {
  4. return f(arg1, arg2)
  5. }
  6. }
  1. powerOf2 := Partial(math.Pow, 2)
  2. sixteen := powerOf2(4)

PHP

  1. function partial($func, $arg1) {
  2. return function(...$args) use ($func, $arg1) {
  3. array_unshift($args, $arg1);
  4. return call_user_func_array($func, $args);
  5. };
  6. }
普通の関数に対して
  1. $powerOf2 = partial('pow', 2);
  2. $sixteen = $powerOf2(4);
クロージャに対して
  1. $pow = function($base, $exp) { return pow($base, $exp); };
  2. $powerOf2 = partial($pow, 2);
  3. $sixteen = $powerOf2(4);

Perl

  1. sub partial {
  2. my ($func, $arg1) = @_;
  3. sub { $func->($arg1, @_) };
  4. }
  1. sub power {
  2. shift() ** shift();
  3. }
  4. my $power_of_2 = partial(\&power, 2);
  5. my $sixteen = $power_of_2->(4);

カリー化(引数の部分適用を行うための関数を作る)を行う関数

Groovy

  1. // 引数が2つの場合
  2. def curry(func) {
  3. { arg1 -> { arg2 -> func(arg1, arg2) } }
  4. }
クロージャに対して
  1. def curriedPower = curry { x, y -> x ** y }
  2. def powerOf2 = curriedPower(2)
  3. def sixteen = powerOf2(4)
メソッドに対して
  1. def power(x, y) { x ** y }
  2. def curriedPower = curry(this.&power)
  3. def powerOf2 = curriedPower(2)
  4. def sixteen = powerOf2(4)

Scala

  1. // 引数が2つの場合
  2. def curry[T1, T2, TResult](func: => (T1, T2) => TResult) = func.curried
クロージャに対して
  1. val power = (x: Double, y: Double) => Math.pow(x, y) // (Double, Double) => Double
  2. val curriedPower = curry(power) // (Double) => (Double) => Double
  3. val powerOf2 = curriedPower(2) // (Double) => Double
  4. val sixteen = powerOf2(4) // 16.0
メソッドに対して
  1. val curriedPower = curry(Math.pow _) // (Double) => (Double) => Double
  2. val powerOf2 = curriedPower(2) // (Double) => Double
  3. val sixteen = powerOf2(4) // 16.0

Erlang

  1. %% 前述の partial 関数を使う
  2. %% 引数が2つの場合
  3. curry(F) ->
  4. fun(Arg1) -> partial(F, Arg1) end.
  1. CurriedPower = curry(fun math:pow/2),
  2. PowerOf2 = CurriedPower(2),
  3. Sixteen = PowerOf2(4),

F#

  1. // 引数が2つの場合
  2. let curry (f : 'a * 'b -> 'c) = fun (a : 'a) -> fun (b : 'b) -> f(a, b)
  1. let curriedPower = curry Math.Pow // float -> float -> float
  2. let powerOf2 = curriedPower 2.0 // float -> float
  3. let sixteen = powerOf2 4.0 // 16.0

C#

  1. // 前述の Partial メソッドを使う
  2. // 引数が2つの場合
  3. public static Func<T1, Func<T2, TResult>> Curry<T1, T2, TResult>(this Func<T1, T2, TResult> func) {
  4. return (arg1) => Partial<T1, T2, TResult>(func, arg1);
  5. }
  1. var curriedPower = Curry<double, double, double>(Math.Pow); // Func<double, Func<double, double>>
  2. var powerOf2 = curriedPower(2); // Func<double, double>
  3. double sixteen = powerOf2(4); // 16.0
  1. Func<double, double, double> power = Math.Pow;
  2. var curriedPower = power.Curry(); // Func<double, Func<double, double>>
  3. var powerOf2 = curriedPower(2); // Func<double, double>
  4. double sixteen = powerOf2(4); // 16.0

Go

  1. // 前述の Partial 関数を使う
  2. // 引数が2つで float64 の場合
  3. func Curry(f func(float64, float64) float64) func(float64) func(float64) float64 {
  4. return func(arg1 float64) func(float64) float64 {
  5. return Partial(f, arg1)
  6. }
  7. }
  1. curriedPower := Curry(math.Pow)
  2. powerOf2 := curriedPower(2)
  3. sixteen := powerOf2(4)

TypeScript

Underscore を使った場合
  1. // import * as _ from 'underscore';
  2. function curry<T1, T2, R>(f: (arg1: T1, arg2: T2) => R) {
  3. return (arg1: T1) => _.partial(f, arg1);
  4. }
  1. let curriedPower = curry(Math.pow);
  2. let powerOf2 = curriedPower(2);
  3. let sixteen = powerOf2(4);

JavaScript

Underscore を使った場合
  1. // const _ = require('underscore');
  2. function curry(f) {
  3. return arg1 => _.partial(f, arg1);
  4. }
  1. let curriedPower = curry(Math.pow);
  2. let powerOf2 = curriedPower(2);
  3. let sixteen = powerOf2(4);

CoffeeScript

Underscore を使った場合
  1. # _ = require('underscore');
  2. curry = (f) -> (arg1) -> _.partial f, arg1
  1. curriedPower = curry Math.pow
  2. powerOf2 = curriedPower 2
  3. sixteen = powerOf2 4

Ruby

メソッドに対して
  1. def power(x, y)
  2. x ** y
  3. end
  4. curried_power = method(:power).to_proc.curry #=> #<Proc:~>
  5. power_of_2 = curried_power[2] #=> #<Proc:~>
  6. sixteen = power_of_2[4] #=> 16
ブロックに対して
  1. power = proc {|x, y| x ** y } #=> #<Proc:~>
  2. curried_power = power.curry #=> #<Proc:~>
  3. power_of_2 = curried_power[2] #=> #<Proc:~>
  4. sixteen = power_of_2[4] #=> 16

Python

  1. # import functools
  2. # 引数が2つの場合
  3. def curry(func):
  4. return lambda arg1: functools.partial(func, arg1)
  1. curriedPower = curry(pow)
  2. powerOf2 = curriedPower(2)
  3. sixteen = powerOf2(4)

PHP

  1. // 前述の partial 関数を使う
  2. function curry($func) {
  3. return function($arg1) use ($func) {
  4. return partial($func, $arg1);
  5. };
  6. }
普通の関数に対して
  1. $curriedPower = curry('pow');
  2. $powerOf2 = $curriedPower(2);
  3. $sixteen = $powerOf2(4);
クロージャに対して
  1. $pow = function($base, $exp) { return pow($base, $exp); };
  2. $curriedPower = curry($pow);
  3. $powerOf2 = $curriedPower(2);
  4. $sixteen = $powerOf2(4);

Perl

  1. # 前述の partial 関数を使う
  2. # 引数が2つの場合
  3. sub curry {
  4. my $func = shift;
  5. sub { partial($func, shift) };
  6. }
  1. sub power {
  2. shift() ** shift();
  3. }
  4. my $curried_power = curry(\&power);
  5. my $power_of_2 = $curried_power->(2);
  6. my $sixteen = $power_of_2->(4);

メソッドが呼び出されたときに特定の処理が行われるようにする

Python

  1. # import traceback
  2. def log_when_called(f):
  3. def _(*args):
  4. print('---- ' + repr(f) + ' called.')
  5. return f(*args)
  6. func_name = traceback.extract_stack()[-1][2] # このメソッド(log_when_called)の名前
  7. _.__name__ = func_name + '+' + f.__name__
  8. return _
  9. @log_when_called
  10. def double(x):
  11. return x * 2
  12. @log_when_called
  13. def triple(x):
  14. return x * 3;

戻る

目次

ローカル変数の名前を全て出力する Java Groovy Kotlin Scala Erlang Haskell PowerShell F# C# C++ Go Rust Dart TypeScript JavaScript CoffeeScript Ruby Python PHP Perl
指定された処理を指定された回数だけ繰り返し実行する関数 Java Groovy Kotlin Scala Erlang Haskell PowerShell F# C# C++ Go Rust Dart TypeScript JavaScript CoffeeScript Ruby Python PHP Perl
外部のプログラムを実行し、標準出力への出力内容と終了コードを取得する Java Groovy Kotlin Scala Erlang Haskell PowerShell F# C# C++ Go Rust Dart TypeScript JavaScript CoffeeScript Ruby Python PHP Perl
外部のプログラムの標準入力にファイルの内容を渡し、標準出力への出力内容を別のファイルに書き込む Java Groovy Kotlin Scala Erlang Haskell PowerShell F# C# C++ Go Rust Dart TypeScript JavaScript CoffeeScript Ruby Python PHP Perl
ユニットテスト Java Groovy Kotlin Scala Erlang Haskell PowerShell F# C# C++ Go Rust Dart TypeScript JavaScript CoffeeScript Ruby Python PHP Perl
引数の部分適用 Java Groovy Kotlin Scala Erlang Haskell PowerShell F# C# C++ Go Rust Dart TypeScript JavaScript CoffeeScript Ruby Python PHP Perl
引数の部分適用を行う関数 Java Groovy Kotlin Scala Erlang Haskell PowerShell F# C# C++ Go Rust Dart TypeScript JavaScript CoffeeScript Ruby Python PHP Perl
カリー化(引数の部分適用を行うための関数を作る)を行う関数 Java Groovy Kotlin Scala Erlang Haskell PowerShell F# C# C++ Go Rust Dart TypeScript JavaScript CoffeeScript Ruby Python PHP Perl
メソッドが呼び出されたときに特定の処理が行われるようにする Java Groovy Kotlin Scala Erlang Haskell PowerShell F# C# C++ Go Rust Dart TypeScript JavaScript CoffeeScript Ruby Python PHP Perl