Simple Comparisons

Table of Contents

Intro

I often find myself browsing http://rosettacode.org/wiki/Rosetta_Code however the results there are often quite advanced.

As a fun experiment, I'm going to do similar here (comparing different language/syntax for a variety of tasks) but try to keep to simple/trivial tasks and avoid going into more advanced cases.

This will therefore serve as a solid base/reference for when going from one language to another (and needing to perform trivial task).

Define function to print Hello World to stdout then call it

(defn hello-world []
  (prn "Hello World"))

(hello-world)
(defn hello-world []
  (pp "Hello World"))

(hello-world)
#include <stdio.h>

void hello_world ()
{
  printf ("Hello World");
}

hello_world ();
function helloWorld () {
  console.log("Hello World")
}

helloWorld ()
(defun hello-world ()
  (prin1 "Hello World"))

(hello-world)
-module(hw).

hello_world() ->
  io:format("Hello World").

hw:hello_world().

Define or alias to function to add two numbers then call on 1, 2 storing in x

(def sum +)

(def x (sum 1 2))
(def sum +)

(def x (sum 1 2))
int sum (int a, int b) { return a + b; }

int x = sum (1, 2);
function sum (a, b) { return a + b; }

const x = sum (1, 2)
(defun sum (a b) (+ a b))

(defvar x (sum 1 2))
-module(y).
sum(A,B) -> A + B.

X = y:sum(1, 2).

Define a function to read a file fn and store contents in x

(def my-slurp slurp)

(def x (my-slurp "test.txt"))
(def my-slurp slurp)

(def x (my-slurp "test.txt"))
char *
slurp (char *fn)
{
  FILE *fp;
  char *c;
  char *content = malloc (sizeof (char));
  char line[255];

  fp = fopen (fn, "r");

  while (NULL != (c = fgets (line, 255, fp)))
    {
      content = realloc (content, sizeof (char) * (strlen (c) + strlen (content)));
      strcat (content, c);
    }

  fclose (fp);

  return content;
}

char *x = slurp ("test.txt");
const fs = require('fs')

function slurp (fn) {
  return fs.readFileSync(fn)
}

var x = slurp('test.txt')
function slurp ($fn) {
  return file_get_contents($fn);
}

$x = slurp ('test.txt');
(defun slurp (filename)
  "Read in FILENAME and return as a single string."
  (let ((lines
         (with-open-file
             (stream filename
                     :direction :input
                     :if-does-not-exist :error)
           (when stream
             (loop for line = (read-line stream nil 'eof)
                until (eq line 'eof)
                collect line)))))
    (format nil "~{~a~^~%~}" lines)))

(defvar x (slurp "test.txt"))

Sum of all numbers from 0 to 9

(reduce + (range 10))
(reduce + 0 (range 10))
int i;
int sum = 0;

for (i = 0; i < 10; i++)
  {
    sum += i;
  }
[...Array(10).keys()].reduce((acc, cur) => acc + cur)
for (i = 0; i < 10; i++) {
  sum += i;
}
lists:foldl(fun (N, Acc) -> N + Acc end, 0, lists:seq(0, 9)).
+/ i.10

End

Author: Matthew Carter

Created: 2020-04-09 Thu 12:05

Validate