WeixiangYan/CodeTransOcean huggingface dataset:
Task: Strip comments from a string


C++: #include <iostream>
#include <string>

std::string strip_white(const std::string& input)
{
   size_t b = input.find_first_not_of(' ');
   if (b == std::string::npos) b = 0;
   return input.substr(b, input.find_last_not_of(' ') + 1 - b);
}

std::string strip_comments(const std::string& input, const std::string& delimiters)
{
   return strip_white(input.substr(0, input.find_first_of(delimiters)));
}
 
int main( ) {
   std::string input;
   std::string delimiters("#;");
   while ( getline(std::cin, input) && !input.empty() ) {
      std::cout << strip_comments(input, delimiters) << std::endl ;
   }
   return 0;
}








COBOL:        identification division.
       program-id. StripComments.

       data division.
       working-storage section.
       01  line-text              pic x(64).

       procedure division.
       main.
           move "apples, pears # and bananas" to line-text
           perform show-striped-text

           move "apples, pears ; and bananas" to line-text
           perform show-striped-text

           stop run
           .
       show-striped-text.
           unstring line-text delimited by "#" or ";" into line-text
           display quote, function trim(line-text), quote
           .
Task: Strip comments from a string





Java: import java.io.*;

public class StripLineComments{
    public static void main( String[] args ){
	if( args.length < 1 ){
	    System.out.println("Usage: java StripLineComments StringToProcess");
	}
	else{
	    String inputFile = args[0];
	    String input = "";
	    try{
		BufferedReader reader = new BufferedReader( new FileReader( inputFile ) );
		String line = "";
		while((line = reader.readLine()) != null){
		    System.out.println( line.split("[#;]")[0] );
		}
	    }
	    catch( Exception e ){
		e.printStackTrace();
	    }
	}
    }
}





COBOL:        identification division.
       program-id. StripComments.

       data division.
       working-storage section.
       01  line-text              pic x(64).

       procedure division.
       main.
           move "apples, pears # and bananas" to line-text
           perform show-striped-text

           move "apples, pears ; and bananas" to line-text
           perform show-striped-text

           stop run
           .
       show-striped-text.
           unstring line-text delimited by "#" or ";" into line-text
           display quote, function trim(line-text), quote
           .
Task: Strip comments from a string







Python: def remove_comments(line, sep):
    for s in sep:
        i = line.find(s)
        if i >= 0:
            line = line[:i]
    return line.strip()


print remove_comments('apples ; pears 
print remove_comments('apples ; pears 



COBOL:        identification division.
       program-id. StripComments.

       data division.
       working-storage section.
       01  line-text              pic x(64).

       procedure division.
       main.
           move "apples, pears # and bananas" to line-text
           perform show-striped-text

           move "apples, pears ; and bananas" to line-text
           perform show-striped-text

           stop run
           .
       show-striped-text.
           unstring line-text delimited by "#" or ";" into line-text
           display quote, function trim(line-text), quote
           .
Task: Strip comments from a string








VB: Function strip_comments(s,char)
	If InStr(1,s,char) > 0 Then
		arr = Split(s,char)
		strip_comments = RTrim(arr(0))
	Else
		strip_comments = s
	End If
End Function

WScript.StdOut.WriteLine strip_comments("apples, pears # and bananas","#")
WScript.StdOut.WriteLine strip_comments("apples, pears ; and bananas",";")


COBOL:        identification division.
       program-id. StripComments.

       data division.
       working-storage section.
       01  line-text              pic x(64).

       procedure division.
       main.
           move "apples, pears # and bananas" to line-text
           perform show-striped-text

           move "apples, pears ; and bananas" to line-text
           perform show-striped-text

           stop run
           .
       show-striped-text.
           unstring line-text delimited by "#" or ";" into line-text
           display quote, function trim(line-text), quote
           .
Task: Strip comments from a string




Go: package main

import (
	"fmt"
	"strings"
	"unicode"
)

const commentChars = "#;"

func stripComment(source string) string {
	if cut := strings.IndexAny(source, commentChars); cut >= 0 {
		return strings.TrimRightFunc(source[:cut], unicode.IsSpace)
	}
	return source
}

func main() {
	for _, s := range []string{
		"apples, pears # and bananas",
		"apples, pears ; and bananas",
		"no bananas",
	} {
		fmt.Printf("source:   %q\n", s)
		fmt.Printf("stripped: %q\n", stripComment(s))
	}
}






COBOL:        identification division.
       program-id. StripComments.

       data division.
       working-storage section.
       01  line-text              pic x(64).

       procedure division.
       main.
           move "apples, pears # and bananas" to line-text
           perform show-striped-text

           move "apples, pears ; and bananas" to line-text
           perform show-striped-text

           stop run
           .
       show-striped-text.
           unstring line-text delimited by "#" or ";" into line-text
           display quote, function trim(line-text), quote
           .
Task: First-class functions



C#: using System;

class Program
{
    static void Main(string[] args)
    {
        var cube = new Func<double, double>(x => Math.Pow(x, 3.0));
        var croot = new Func<double, double>(x => Math.Pow(x, 1 / 3.0));

        var functionTuples = new[]
        {
            (forward: Math.Sin, backward: Math.Asin),
            (forward: Math.Cos, backward: Math.Acos),
            (forward: cube,     backward: croot)
        };

        foreach (var ft in functionTuples)
        {
            Console.WriteLine(ft.backward(ft.forward(0.5)));
        }
    }
}









Ada: with Ada.Float_Text_IO,
     Ada.Integer_Text_IO,
     Ada.Text_IO,
     Ada.Numerics.Elementary_Functions;

procedure First_Class_Functions is
   use Ada.Float_Text_IO,
       Ada.Integer_Text_IO,
       Ada.Text_IO,
       Ada.Numerics.Elementary_Functions;

   function Sqr (X : Float) return Float is
   begin
      return X ** 2;
   end Sqr;

   type A_Function is access function (X : Float) return Float;

   generic
      F, G : A_Function;
   function Compose (X : Float) return Float;

   function Compose (X : Float) return Float is
   begin
      return F (G (X));
   end Compose;

   Functions : array (Positive range <>) of A_Function := (Sin'Access,
                                                           Cos'Access,
                                                           Sqr'Access);
   Inverses  : array (Positive range <>) of A_Function := (Arcsin'Access,
                                                           Arccos'Access,
                                                           Sqrt'Access);
begin
   for I in Functions'Range loop
      declare
         function Identity is new Compose (Functions (I), Inverses (I));
         Test_Value : Float := 0.5;
         Result     : Float;
      begin
         Result := Identity (Test_Value);

         if Result = Test_Value then
            Put      ("Example ");
            Put      (I, Width => 0);
            Put_Line (" is perfect for the given test value.");
         else
            Put      ("Example ");
            Put      (I, Width => 0);
            Put      (" is off by");
            Put      (abs (Result - Test_Value));
            Put_Line (" for the given test value.");
         end if;
      end;
   end loop;
end First_Class_Functions;
Task: First-class functions

C: #include <stdlib.h>
#include <stdio.h>
#include <math.h>
 

typedef double (*Class2Func)(double);
 

double functionA( double v)
{
   return v*v*v;
}
double functionB(double v)
{
   return exp(log(v)/3);
}
 

double Function1( Class2Func f2, double val )
{
    return f2(val);
}
 

Class2Func WhichFunc( int idx)
{
   return (idx < 4) ? &functionA : &functionB;
}
 

Class2Func funcListA[] = {&functionA, &sin, &cos, &tan };
Class2Func funcListB[] = {&functionB, &asin, &acos, &atan };
 

double InvokeComposed( Class2Func f1, Class2Func f2, double val )
{
   return f1(f2(val));
}
 
typedef struct sComposition {
   Class2Func f1;
   Class2Func f2;
} *Composition;
 
Composition Compose( Class2Func f1, Class2Func f2)
{
   Composition comp = malloc(sizeof(struct sComposition));
   comp->f1 = f1;
   comp->f2 = f2;
   return comp;
}
 
double CallComposed( Composition comp, double val )
{
    return comp->f1( comp->f2(val) );
}

 
int main(int argc, char *argv[])
{
   int ix;
   Composition c;
 
   printf("Function1(functionA, 3.0) = %f\n", Function1(WhichFunc(0), 3.0));
 
   for (ix=0; ix<4; ix++) {
       c = Compose(funcListA[ix], funcListB[ix]);
       printf("Compostion %d(0.9) = %f\n", ix, CallComposed(c, 0.9));
   }
 
   return 0;
}











Ada: with Ada.Float_Text_IO,
     Ada.Integer_Text_IO,
     Ada.Text_IO,
     Ada.Numerics.Elementary_Functions;

procedure First_Class_Functions is
   use Ada.Float_Text_IO,
       Ada.Integer_Text_IO,
       Ada.Text_IO,
       Ada.Numerics.Elementary_Functions;

   function Sqr (X : Float) return Float is
   begin
      return X ** 2;
   end Sqr;

   type A_Function is access function (X : Float) return Float;

   generic
      F, G : A_Function;
   function Compose (X : Float) return Float;

   function Compose (X : Float) return Float is
   begin
      return F (G (X));
   end Compose;

   Functions : array (Positive range <>) of A_Function := (Sin'Access,
                                                           Cos'Access,
                                                           Sqr'Access);
   Inverses  : array (Positive range <>) of A_Function := (Arcsin'Access,
                                                           Arccos'Access,
                                                           Sqrt'Access);
begin
   for I in Functions'Range loop
      declare
         function Identity is new Compose (Functions (I), Inverses (I));
         Test_Value : Float := 0.5;
         Result     : Float;
      begin
         Result := Identity (Test_Value);

         if Result = Test_Value then
            Put      ("Example ");
            Put      (I, Width => 0);
            Put_Line (" is perfect for the given test value.");
         else
            Put      ("Example ");
            Put      (I, Width => 0);
            Put      (" is off by");
            Put      (abs (Result - Test_Value));
            Put_Line (" for the given test value.");
         end if;
      end;
   end loop;
end First_Class_Functions;
Task: First-class functions


C++: #include <functional>
#include <algorithm>
#include <iostream>
#include <vector>
#include <cmath>
 
using std::cout;
using std::endl;
using std::vector;
using std::function;
using std::transform;
using std::back_inserter;

typedef function<double(double)> FunType;

vector<FunType> A = {sin, cos, tan, [](double x) { return x*x*x; } };
vector<FunType> B = {asin, acos, atan, [](double x) { return exp(log(x)/3); } };

template <typename A, typename B, typename C>
function<C(A)> compose(function<C(B)> f, function<B(A)> g) {
    return [f,g](A x) { return f(g(x)); };
}

int main() {
    vector<FunType> composedFuns;
    auto exNums = {0.0, 0.2, 0.4, 0.6, 0.8, 1.0};

    transform(B.begin(), B.end(),
                A.begin(),
                back_inserter(composedFuns),
                compose<double, double, double>);

    for (auto num: exNums)
        for (auto fun: composedFuns)
            cout << u8"f\u207B\u00B9.f(" << num << ") = " << fun(num) << endl;

    return 0;
}










Ada: with Ada.Float_Text_IO,
     Ada.Integer_Text_IO,
     Ada.Text_IO,
     Ada.Numerics.Elementary_Functions;

procedure First_Class_Functions is
   use Ada.Float_Text_IO,
       Ada.Integer_Text_IO,
       Ada.Text_IO,
       Ada.Numerics.Elementary_Functions;

   function Sqr (X : Float) return Float is
   begin
      return X ** 2;
   end Sqr;

   type A_Function is access function (X : Float) return Float;

   generic
      F, G : A_Function;
   function Compose (X : Float) return Float;

   function Compose (X : Float) return Float is
   begin
      return F (G (X));
   end Compose;

   Functions : array (Positive range <>) of A_Function := (Sin'Access,
                                                           Cos'Access,
                                                           Sqr'Access);
   Inverses  : array (Positive range <>) of A_Function := (Arcsin'Access,
                                                           Arccos'Access,
                                                           Sqrt'Access);
begin
   for I in Functions'Range loop
      declare
         function Identity is new Compose (Functions (I), Inverses (I));
         Test_Value : Float := 0.5;
         Result     : Float;
      begin
         Result := Identity (Test_Value);

         if Result = Test_Value then
            Put      ("Example ");
            Put      (I, Width => 0);
            Put_Line (" is perfect for the given test value.");
         else
            Put      ("Example ");
            Put      (I, Width => 0);
            Put      (" is off by");
            Put      (abs (Result - Test_Value));
            Put_Line (" for the given test value.");
         end if;
      end;
   end loop;
end First_Class_Functions;
Task: First-class functions




Go: package main

import "math"
import "fmt"


func cube(x float64) float64 { return math.Pow(x, 3) }


type ffType func(float64) float64

func compose(f, g ffType) ffType {
    return func(x float64) float64 {
        return f(g(x))
    }
}

func main() {
    
    funclist := []ffType{math.Sin, math.Cos, cube}
    
    funclisti := []ffType{math.Asin, math.Acos, math.Cbrt}
    for i := 0; i < 3; i++ {
        
        fmt.Println(compose(funclisti[i], funclist[i])(.5))
    }
}








Ada: with Ada.Float_Text_IO,
     Ada.Integer_Text_IO,
     Ada.Text_IO,
     Ada.Numerics.Elementary_Functions;

procedure First_Class_Functions is
   use Ada.Float_Text_IO,
       Ada.Integer_Text_IO,
       Ada.Text_IO,
       Ada.Numerics.Elementary_Functions;

   function Sqr (X : Float) return Float is
   begin
      return X ** 2;
   end Sqr;

   type A_Function is access function (X : Float) return Float;

   generic
      F, G : A_Function;
   function Compose (X : Float) return Float;

   function Compose (X : Float) return Float is
   begin
      return F (G (X));
   end Compose;

   Functions : array (Positive range <>) of A_Function := (Sin'Access,
                                                           Cos'Access,
                                                           Sqr'Access);
   Inverses  : array (Positive range <>) of A_Function := (Arcsin'Access,
                                                           Arccos'Access,
                                                           Sqrt'Access);
begin
   for I in Functions'Range loop
      declare
         function Identity is new Compose (Functions (I), Inverses (I));
         Test_Value : Float := 0.5;
         Result     : Float;
      begin
         Result := Identity (Test_Value);

         if Result = Test_Value then
            Put      ("Example ");
            Put      (I, Width => 0);
            Put_Line (" is perfect for the given test value.");
         else
            Put      ("Example ");
            Put      (I, Width => 0);
            Put      (" is off by");
            Put      (abs (Result - Test_Value));
            Put_Line (" for the given test value.");
         end if;
      end;
   end loop;
end First_Class_Functions;
Task: First-class functions







Python: >>> 
>>> from math import sin, cos, acos, asin
>>> 
>>> cube = lambda x: x * x * x
>>> croot = lambda x: x ** (1/3.0)
>>> 
>>> 
>>> compose = lambda f1, f2: ( lambda x: f1(f2(x)) )
>>> 
>>> funclist = [sin, cos, cube]
>>> funclisti = [asin, acos, croot]
>>> 
>>> [compose(inversef, f)(.5) for f, inversef in zip(funclist, funclisti)]
[0.5, 0.4999999999999999, 0.5]
>>>





Ada: with Ada.Float_Text_IO,
     Ada.Integer_Text_IO,
     Ada.Text_IO,
     Ada.Numerics.Elementary_Functions;

procedure First_Class_Functions is
   use Ada.Float_Text_IO,
       Ada.Integer_Text_IO,
       Ada.Text_IO,
       Ada.Numerics.Elementary_Functions;

   function Sqr (X : Float) return Float is
   begin
      return X ** 2;
   end Sqr;

   type A_Function is access function (X : Float) return Float;

   generic
      F, G : A_Function;
   function Compose (X : Float) return Float;

   function Compose (X : Float) return Float is
   begin
      return F (G (X));
   end Compose;

   Functions : array (Positive range <>) of A_Function := (Sin'Access,
                                                           Cos'Access,
                                                           Sqr'Access);
   Inverses  : array (Positive range <>) of A_Function := (Arcsin'Access,
                                                           Arccos'Access,
                                                           Sqrt'Access);
begin
   for I in Functions'Range loop
      declare
         function Identity is new Compose (Functions (I), Inverses (I));
         Test_Value : Float := 0.5;
         Result     : Float;
      begin
         Result := Identity (Test_Value);

         if Result = Test_Value then
            Put      ("Example ");
            Put      (I, Width => 0);
            Put_Line (" is perfect for the given test value.");
         else
            Put      ("Example ");
            Put      (I, Width => 0);
            Put      (" is off by");
            Put      (abs (Result - Test_Value));
            Put_Line (" for the given test value.");
         end if;
      end;
   end loop;
end First_Class_Functions;
Task: First-class functions

C: #include <stdlib.h>
#include <stdio.h>
#include <math.h>
 

typedef double (*Class2Func)(double);
 

double functionA( double v)
{
   return v*v*v;
}
double functionB(double v)
{
   return exp(log(v)/3);
}
 

double Function1( Class2Func f2, double val )
{
    return f2(val);
}
 

Class2Func WhichFunc( int idx)
{
   return (idx < 4) ? &functionA : &functionB;
}
 

Class2Func funcListA[] = {&functionA, &sin, &cos, &tan };
Class2Func funcListB[] = {&functionB, &asin, &acos, &atan };
 

double InvokeComposed( Class2Func f1, Class2Func f2, double val )
{
   return f1(f2(val));
}
 
typedef struct sComposition {
   Class2Func f1;
   Class2Func f2;
} *Composition;
 
Composition Compose( Class2Func f1, Class2Func f2)
{
   Composition comp = malloc(sizeof(struct sComposition));
   comp->f1 = f1;
   comp->f2 = f2;
   return comp;
}
 
double CallComposed( Composition comp, double val )
{
    return comp->f1( comp->f2(val) );
}

 
int main(int argc, char *argv[])
{
   int ix;
   Composition c;
 
   printf("Function1(functionA, 3.0) = %f\n", Function1(WhichFunc(0), 3.0));
 
   for (ix=0; ix<4; ix++) {
       c = Compose(funcListA[ix], funcListB[ix]);
       printf("Compostion %d(0.9) = %f\n", ix, CallComposed(c, 0.9));
   }
 
   return 0;
}
Task: First-class functions



C#: using System;

class Program
{
    static void Main(string[] args)
    {
        var cube = new Func<double, double>(x => Math.Pow(x, 3.0));
        var croot = new Func<double, double>(x => Math.Pow(x, 1 / 3.0));

        var functionTuples = new[]
        {
            (forward: Math.Sin, backward: Math.Asin),
            (forward: Math.Cos, backward: Math.Acos),
            (forward: cube,     backward: croot)
        };

        foreach (var ft in functionTuples)
        {
            Console.WriteLine(ft.backward(ft.forward(0.5)));
        }
    }
}
Task: First-class functions


C++: #include <functional>
#include <algorithm>
#include <iostream>
#include <vector>
#include <cmath>
 
using std::cout;
using std::endl;
using std::vector;
using std::function;
using std::transform;
using std::back_inserter;

typedef function<double(double)> FunType;

vector<FunType> A = {sin, cos, tan, [](double x) { return x*x*x; } };
vector<FunType> B = {asin, acos, atan, [](double x) { return exp(log(x)/3); } };

template <typename A, typename B, typename C>
function<C(A)> compose(function<C(B)> f, function<B(A)> g) {
    return [f,g](A x) { return f(g(x)); };
}

int main() {
    vector<FunType> composedFuns;
    auto exNums = {0.0, 0.2, 0.4, 0.6, 0.8, 1.0};

    transform(B.begin(), B.end(),
                A.begin(),
                back_inserter(composedFuns),
                compose<double, double, double>);

    for (auto num: exNums)
        for (auto fun: composedFuns)
            cout << u8"f\u207B\u00B9.f(" << num << ") = " << fun(num) << endl;

    return 0;
}
Task: First-class functions





Java: import java.util.ArrayList;

public class FirstClass{
	
	public interface Function<A,B>{
		B apply(A x);
	}
	
	public static <A,B,C> Function<A, C> compose(
			final Function<B, C> f, final Function<A, B> g) {
		return new Function<A, C>() {
			@Override public C apply(A x) {
				return f.apply(g.apply(x));
			}
		};
	}
	 
	public static void main(String[] args){
		ArrayList<Function<Double, Double>> functions =
			new ArrayList<Function<Double,Double>>();
		
		functions.add(
				new Function<Double, Double>(){
					@Override public Double apply(Double x){
						return Math.cos(x);
					}
				});
		functions.add(
				new Function<Double, Double>(){
					@Override public Double apply(Double x){
						return Math.tan(x);
					}
				});
		functions.add(
				new Function<Double, Double>(){
					@Override public Double apply(Double x){
						return x * x;
					}
				});
		
		ArrayList<Function<Double, Double>> inverse = new ArrayList<Function<Double,Double>>();
		
		inverse.add(
				new Function<Double, Double>(){
					@Override public Double apply(Double x){
						return Math.acos(x);
					}
				});
		inverse.add(
				new Function<Double, Double>(){
					@Override public Double apply(Double x){
						return Math.atan(x);
					}
				});
		inverse.add(
				new Function<Double, Double>(){
					@Override public Double apply(Double x){
						return Math.sqrt(x);
					}
				});
		System.out.println("Compositions:");
		for(int i = 0; i < functions.size(); i++){
			System.out.println(compose(functions.get(i), inverse.get(i)).apply(0.5));
		}
		System.out.println("Hard-coded compositions:");
		System.out.println(Math.cos(Math.acos(0.5)));
		System.out.println(Math.tan(Math.atan(0.5)));
		System.out.println(Math.pow(Math.sqrt(0.5), 2));
	}
}
Task: First-class functions







Python: >>> 
>>> from math import sin, cos, acos, asin
>>> 
>>> cube = lambda x: x * x * x
>>> croot = lambda x: x ** (1/3.0)
>>> 
>>> 
>>> compose = lambda f1, f2: ( lambda x: f1(f2(x)) )
>>> 
>>> funclist = [sin, cos, cube]
>>> funclisti = [asin, acos, croot]
>>> 
>>> [compose(inversef, f)(.5) for f, inversef in zip(funclist, funclisti)]
[0.5, 0.4999999999999999, 0.5]
>>>
Task: First-class functions




Go: package main

import "math"
import "fmt"


func cube(x float64) float64 { return math.Pow(x, 3) }


type ffType func(float64) float64

func compose(f, g ffType) ffType {
    return func(x float64) float64 {
        return f(g(x))
    }
}

func main() {
    
    funclist := []ffType{math.Sin, math.Cos, cube}
    
    funclisti := []ffType{math.Asin, math.Acos, math.Cbrt}
    for i := 0; i < 3; i++ {
        
        fmt.Println(compose(funclisti[i], funclist[i])(.5))
    }
}
Task: First-class functions






PHP: $compose = function ($f, $g) {
    return function ($x) use ($f, $g) {
        return $f($g($x));
    };
};

$fn  = array('sin', 'cos', function ($x) { return pow($x, 3); });
$inv = array('asin', 'acos', function ($x) { return pow($x, 1/3); });

for ($i = 0; $i < 3; $i++) {
    $f = $compose($inv[$i], $fn[$i]);
    echo $f(0.5), PHP_EOL;
}