WeixiangYan/CodeTransOcean huggingface dataset:
Task: Horizontal sundial calculations





Java: import java.util.Scanner;

public class Sundial {
    public static void main(String[] args) {
        double lat, slat, lng, ref;
        Scanner sc = new Scanner(System.in);

        System.out.print("Enter latitude: ");
        lat = sc.nextDouble();
        System.out.print("Enter longitude: ");
        lng = sc.nextDouble();
        System.out.print("Enter legal meridian: ");
        ref = sc.nextDouble();
        System.out.println();

        slat = Math.sin(Math.toRadians(lat));
        System.out.printf("sine of latitude: %.3f\n", slat);
        System.out.printf("diff longitude: %.3f\n\n", lng - ref);

        System.out.printf("Hour, sun hour angle, dial hour line angle from 6am to 6pm\n");

        for (int h = -6; h <= 6; h++) {
            double hla, hra, hraRad;
            hra = 15.0 * h;
            hra = hra - lng + ref;
            hraRad = Math.toRadians(hra);
            hla = Math.toDegrees(Math.atan2(Math.sin(hraRad)*Math.sin(Math.toRadians(lat)), Math.cos(hraRad)));
            System.out.printf("HR= %3d;  \t  HRA=%7.3f;  \t  HLA= %7.3f\n",
                    h, hra, hla);
        }
    }
}



Python: from __future__ import print_function
import math
try: raw_input
except: raw_input = input

lat = float(raw_input("Enter latitude       => "))
lng = float(raw_input("Enter longitude      => "))
ref = float(raw_input("Enter legal meridian => "))
print()

slat = math.sin(math.radians(lat))
print("    sine of latitude:   %.3f" % slat)
print("    diff longitude:     %.3f" % (lng-ref))
print()
print("Hour, sun hour angle, dial hour line angle from 6am to 6pm")

for h in range(-6, 7):
  hra = 15 * h
  hra -= lng - ref
  hla = math.degrees(math.atan(slat * math.tan(math.radians(hra))))
  print("HR=%3d; HRA=%7.3f; HLA=%7.3f" % (h, hra, hla))
Task: Horizontal sundial calculations




Go: package main

import (
    "fmt"
    "math"
    "os"
)

func getnum(prompt string) (r float64) {
    fmt.Print(prompt)
    if _, err := fmt.Scan(&r); err != nil {
        fmt.Println(err)
        os.Exit(-1)
    }
    return
}

func main() {
    lat := getnum("Enter latitude       => ")
    lng := getnum("Enter longitude      => ")
    ref := getnum("Enter legal meridian => ")
    slat := math.Sin(lat * math.Pi / 180)
    diff := lng - ref
    fmt.Println("\n    sine of latitude:   ", slat)
    fmt.Println("    diff longitude:     ", diff)
    fmt.Println("\nHour, sun hour angle, dial hour line angle from 6am to 6pm")
    for h := -6.; h <= 6; h++ {
        hra := 15*h - diff
        s, c := math.Sincos(hra * math.Pi / 180)
        hla := math.Atan2(slat*s, c) * 180 / math.Pi
        fmt.Printf("%2.0f %8.3f %8.3f\n", h, hra, hla)
    }
}




Python: from __future__ import print_function
import math
try: raw_input
except: raw_input = input

lat = float(raw_input("Enter latitude       => "))
lng = float(raw_input("Enter longitude      => "))
ref = float(raw_input("Enter legal meridian => "))
print()

slat = math.sin(math.radians(lat))
print("    sine of latitude:   %.3f" % slat)
print("    diff longitude:     %.3f" % (lng-ref))
print()
print("Hour, sun hour angle, dial hour line angle from 6am to 6pm")

for h in range(-6, 7):
  hra = 15 * h
  hra -= lng - ref
  hla = math.degrees(math.atan(slat * math.tan(math.radians(hra))))
  print("HR=%3d; HRA=%7.3f; HLA=%7.3f" % (h, hra, hla))
Task: Horizontal sundial calculations



C#: using System;

namespace RosettaCode
{
  internal sealed class Program
  {
    private static void Main()
    {
      Func<double> getDouble = () => Convert.ToDouble(Console.ReadLine());
      double h = 0, lat, lng, lme, slat, hra, hla;

      Console.Write("Enter latitude       => ");
      lat = getDouble();
      Console.Write("Enter longitude      => ");
      lng = getDouble();
      Console.Write("Enter legal meridian => ");
      lme = getDouble();

      slat = Math.Sin(lat*2*Math.PI/360);
      Console.WriteLine("\n    sine of latitude:   {0:0.000}", slat);
      Console.WriteLine("    diff longitude:     {0:0.000}\n", lng-lme);
      Console.WriteLine("Hour, sun hour angle, dial hour line angle from 6am to 6pm");
      for (h = -6; h<6; h++)
      {
        hra = 15*h;
        hra -= lng-lme;
        hla = Math.Atan(slat*Math.Tan(hra*2*Math.PI/360))*360/(2*Math.PI);
        Console.WriteLine("HR= {0,7:0.000}; HRA {1,7:0.000}; HLA= {2,7:0.000}", h, hra, hla);
      }
    }
  }
}


Go: package main

import (
    "fmt"
    "math"
    "os"
)

func getnum(prompt string) (r float64) {
    fmt.Print(prompt)
    if _, err := fmt.Scan(&r); err != nil {
        fmt.Println(err)
        os.Exit(-1)
    }
    return
}

func main() {
    lat := getnum("Enter latitude       => ")
    lng := getnum("Enter longitude      => ")
    ref := getnum("Enter legal meridian => ")
    slat := math.Sin(lat * math.Pi / 180)
    diff := lng - ref
    fmt.Println("\n    sine of latitude:   ", slat)
    fmt.Println("    diff longitude:     ", diff)
    fmt.Println("\nHour, sun hour angle, dial hour line angle from 6am to 6pm")
    for h := -6.; h <= 6; h++ {
        hra := 15*h - diff
        s, c := math.Sincos(hra * math.Pi / 180)
        hla := math.Atan2(slat*s, c) * 180 / math.Pi
        fmt.Printf("%2.0f %8.3f %8.3f\n", h, hra, hla)
    }
}
Task: Horizontal sundial calculations



C#: using System;

namespace RosettaCode
{
  internal sealed class Program
  {
    private static void Main()
    {
      Func<double> getDouble = () => Convert.ToDouble(Console.ReadLine());
      double h = 0, lat, lng, lme, slat, hra, hla;

      Console.Write("Enter latitude       => ");
      lat = getDouble();
      Console.Write("Enter longitude      => ");
      lng = getDouble();
      Console.Write("Enter legal meridian => ");
      lme = getDouble();

      slat = Math.Sin(lat*2*Math.PI/360);
      Console.WriteLine("\n    sine of latitude:   {0:0.000}", slat);
      Console.WriteLine("    diff longitude:     {0:0.000}\n", lng-lme);
      Console.WriteLine("Hour, sun hour angle, dial hour line angle from 6am to 6pm");
      for (h = -6; h<6; h++)
      {
        hra = 15*h;
        hra -= lng-lme;
        hla = Math.Atan(slat*Math.Tan(hra*2*Math.PI/360))*360/(2*Math.PI);
        Console.WriteLine("HR= {0,7:0.000}; HRA {1,7:0.000}; HLA= {2,7:0.000}", h, hra, hla);
      }
    }
  }
}





Python: from __future__ import print_function
import math
try: raw_input
except: raw_input = input

lat = float(raw_input("Enter latitude       => "))
lng = float(raw_input("Enter longitude      => "))
ref = float(raw_input("Enter legal meridian => "))
print()

slat = math.sin(math.radians(lat))
print("    sine of latitude:   %.3f" % slat)
print("    diff longitude:     %.3f" % (lng-ref))
print()
print("Hour, sun hour angle, dial hour line angle from 6am to 6pm")

for h in range(-6, 7):
  hra = 15 * h
  hra -= lng - ref
  hla = math.degrees(math.atan(slat * math.tan(math.radians(hra))))
  print("HR=%3d; HRA=%7.3f; HLA=%7.3f" % (h, hra, hla))
Task: Horizontal sundial calculations




Go: package main

import (
    "fmt"
    "math"
    "os"
)

func getnum(prompt string) (r float64) {
    fmt.Print(prompt)
    if _, err := fmt.Scan(&r); err != nil {
        fmt.Println(err)
        os.Exit(-1)
    }
    return
}

func main() {
    lat := getnum("Enter latitude       => ")
    lng := getnum("Enter longitude      => ")
    ref := getnum("Enter legal meridian => ")
    slat := math.Sin(lat * math.Pi / 180)
    diff := lng - ref
    fmt.Println("\n    sine of latitude:   ", slat)
    fmt.Println("    diff longitude:     ", diff)
    fmt.Println("\nHour, sun hour angle, dial hour line angle from 6am to 6pm")
    for h := -6.; h <= 6; h++ {
        hra := 15*h - diff
        s, c := math.Sincos(hra * math.Pi / 180)
        hla := math.Atan2(slat*s, c) * 180 / math.Pi
        fmt.Printf("%2.0f %8.3f %8.3f\n", h, hra, hla)
    }
}


Java: import java.util.Scanner;

public class Sundial {
    public static void main(String[] args) {
        double lat, slat, lng, ref;
        Scanner sc = new Scanner(System.in);

        System.out.print("Enter latitude: ");
        lat = sc.nextDouble();
        System.out.print("Enter longitude: ");
        lng = sc.nextDouble();
        System.out.print("Enter legal meridian: ");
        ref = sc.nextDouble();
        System.out.println();

        slat = Math.sin(Math.toRadians(lat));
        System.out.printf("sine of latitude: %.3f\n", slat);
        System.out.printf("diff longitude: %.3f\n\n", lng - ref);

        System.out.printf("Hour, sun hour angle, dial hour line angle from 6am to 6pm\n");

        for (int h = -6; h <= 6; h++) {
            double hla, hra, hraRad;
            hra = 15.0 * h;
            hra = hra - lng + ref;
            hraRad = Math.toRadians(hra);
            hla = Math.toDegrees(Math.atan2(Math.sin(hraRad)*Math.sin(Math.toRadians(lat)), Math.cos(hraRad)));
            System.out.printf("HR= %3d;  \t  HRA=%7.3f;  \t  HLA= %7.3f\n",
                    h, hra, hla);
        }
    }
}
Task: Horizontal sundial calculations


C++: #include <cmath>
#include <iostream>
#include <numbers>


static const double DegreesPerHour = 15.0;
static const double DegreesPerRadian = 180.0 * std::numbers::inv_pi;


struct SundialCalculation
{
  double HourAngle;
  double HourLineAngle;
};


class Sundial
{
  
  double m_sinLatitude;
  double m_timeZoneCorrection;
    
public:
  Sundial(double latitude, double longitude, double legalMeridian) noexcept
    : m_sinLatitude(sin(latitude / DegreesPerRadian))
    , m_timeZoneCorrection(legalMeridian - longitude) {}

  SundialCalculation CalculateShadow(double hoursSinceNoon) const noexcept
  {
    double hourAngle = hoursSinceNoon * DegreesPerHour + m_timeZoneCorrection;
    double hourAngleRad = hourAngle / DegreesPerRadian;
    double hlaRad = atan2(m_sinLatitude * sin(hourAngleRad), cos(hourAngleRad));
    double hourLineAngle = hlaRad * DegreesPerRadian;
    return SundialCalculation {hourAngle, hourLineAngle};
  }
};

int main()
{
  double latitude, longitude, legalMeridian;
  std::cout << "Enter latitude:";
  std::cin >> latitude;
  std::cout << "Enter longitude:";
  std::cin >> longitude;
  std::cout << "Enter legal meridian:";
  std::cin >> legalMeridian;
  
  
  const Sundial sundial(latitude, longitude, legalMeridian);
  for(int hour = -6; hour < 7; ++hour)
  {
    
    auto result = sundial.CalculateShadow(hour);

    
    auto amOrPm = hour < 0 ? "am" : "pm";
    auto hourString = std::to_string(hour < 1 ? 12 + hour : hour);
    std::cout << hourString << amOrPm << 
    " - sun hour angle:" << result.HourAngle <<
    ", dial hour line angle:" << result.HourLineAngle << "\n";
  }
}






Python: from __future__ import print_function
import math
try: raw_input
except: raw_input = input

lat = float(raw_input("Enter latitude       => "))
lng = float(raw_input("Enter longitude      => "))
ref = float(raw_input("Enter legal meridian => "))
print()

slat = math.sin(math.radians(lat))
print("    sine of latitude:   %.3f" % slat)
print("    diff longitude:     %.3f" % (lng-ref))
print()
print("Hour, sun hour angle, dial hour line angle from 6am to 6pm")

for h in range(-6, 7):
  hra = 15 * h
  hra -= lng - ref
  hla = math.degrees(math.atan(slat * math.tan(math.radians(hra))))
  print("HR=%3d; HRA=%7.3f; HLA=%7.3f" % (h, hra, hla))
Task: Polynomial long division


C++: #include <iostream>
#include <iterator>
#include <vector>

using namespace std;
typedef vector<double> Poly;




void Print(char name, const Poly &A) {
	cout << name << "(" << A.size()-1 << ") = [ ";
	copy(A.begin(), A.end(), ostream_iterator<decltype(A[0])>(cout, " "));
	cout << "]\n";
}

int main() {
	Poly N, D, d, q, r;        
	size_t dN, dD, dd, dq, dr; 
	size_t i;                  

	
	cout << "Enter the degree of N: ";
	cin >> dN;
	cout << "Enter the degree of D: "; 
	cin >> dD;
	dq = dN-dD;  
	dr = dN-dD;

	if( dD < 1 || dN < 1 ) {
		cerr << "Error: degree of D and N must be positive.\n";
		return 1;
	}

	
	N.resize(dN+1);
	cout << "Enter the coefficients of N:"<<endl;  
	for ( i = 0; i <= dN; i++ ) {
		cout << "N[" << i << "]= ";
		cin >> N[i];
	}

	D.resize(dN+1);
	cout << "Enter the coefficients of D:"<<endl;	
	for ( i = 0; i <= dD; i++ ) {
		cout << "D[" << i << "]= ";
		cin >> D[i];
	}

	d.resize(dN+1);
	q.resize(dq+1);
	r.resize(dr+1);

	cout << "-- Procedure --" << endl << endl;
	if( dN >= dD ) {
		while(dN >= dD) {
			
			d.assign(d.size(), 0);

			for( i = 0 ; i <= dD ; i++ )
				d[i+dN-dD] = D[i];
			dd = dN;

			Print( 'd', d );

			
			q[dN-dD] = N[dN]/d[dd];

			Print( 'q', q );

			
			for( i = 0 ; i < dq + 1 ; i++ )
				d[i] = d[i] * q[dN-dD];

			Print( 'd', d );

			
			for( i = 0 ; i < dN + 1 ; i++ )
				N[i] = N[i] - d[i];
			dN--;

			Print( 'N', N );
			cout << "-----------------------" << endl << endl;

		}
	}

	
	for( i = 0 ; i <= dN ; i++ )
		r[i] = N[i];

	cout << "=========================" << endl << endl;
	cout << "-- Result --" << endl << endl;

	Print( 'q', q );
	Print( 'r', r );
}






Python: 

from itertools import izip

def degree(poly):
    while poly and poly[-1] == 0:
        poly.pop()   
    return len(poly)-1

def poly_div(N, D):
    dD = degree(D)
    dN = degree(N)
    if dD < 0: raise ZeroDivisionError
    if dN >= dD:
        q = [0] * dN
        while dN >= dD:
            d = [0]*(dN - dD) + D
            mult = q[dN - dD] = N[-1] / float(d[-1])
            d = [coeff*mult for coeff in d]
            N = [coeffN - coeffd for coeffN, coeffd in izip(N, d)]
            dN = degree(N)
        r = N
    else:
        q = [0]
        r = N
    return q, r

if __name__ == '__main__':
    print "POLYNOMIAL LONG DIVISION"
    N = [-42, 0, -12, 1]
    D = [-3, 1, 0, 0]
    print "  %s / %s =" % (N,D),
    print " %s remainder %s" % poly_div(N, D)
Task: Polynomial long division


C++: #include <iostream>
#include <iterator>
#include <vector>

using namespace std;
typedef vector<double> Poly;




void Print(char name, const Poly &A) {
	cout << name << "(" << A.size()-1 << ") = [ ";
	copy(A.begin(), A.end(), ostream_iterator<decltype(A[0])>(cout, " "));
	cout << "]\n";
}

int main() {
	Poly N, D, d, q, r;        
	size_t dN, dD, dd, dq, dr; 
	size_t i;                  

	
	cout << "Enter the degree of N: ";
	cin >> dN;
	cout << "Enter the degree of D: "; 
	cin >> dD;
	dq = dN-dD;  
	dr = dN-dD;

	if( dD < 1 || dN < 1 ) {
		cerr << "Error: degree of D and N must be positive.\n";
		return 1;
	}

	
	N.resize(dN+1);
	cout << "Enter the coefficients of N:"<<endl;  
	for ( i = 0; i <= dN; i++ ) {
		cout << "N[" << i << "]= ";
		cin >> N[i];
	}

	D.resize(dN+1);
	cout << "Enter the coefficients of D:"<<endl;	
	for ( i = 0; i <= dD; i++ ) {
		cout << "D[" << i << "]= ";
		cin >> D[i];
	}

	d.resize(dN+1);
	q.resize(dq+1);
	r.resize(dr+1);

	cout << "-- Procedure --" << endl << endl;
	if( dN >= dD ) {
		while(dN >= dD) {
			
			d.assign(d.size(), 0);

			for( i = 0 ; i <= dD ; i++ )
				d[i+dN-dD] = D[i];
			dd = dN;

			Print( 'd', d );

			
			q[dN-dD] = N[dN]/d[dd];

			Print( 'q', q );

			
			for( i = 0 ; i < dq + 1 ; i++ )
				d[i] = d[i] * q[dN-dD];

			Print( 'd', d );

			
			for( i = 0 ; i < dN + 1 ; i++ )
				N[i] = N[i] - d[i];
			dN--;

			Print( 'N', N );
			cout << "-----------------------" << endl << endl;

		}
	}

	
	for( i = 0 ; i <= dN ; i++ )
		r[i] = N[i];

	cout << "=========================" << endl << endl;
	cout << "-- Result --" << endl << endl;

	Print( 'q', q );
	Print( 'r', r );
}



Go: package main

import "fmt"

func main() {
    n := []float64{-42, 0, -12, 1}
    d := []float64{-3, 1}
    fmt.Println("N:", n)
    fmt.Println("D:", d)
    q, r, ok := pld(n, d)
    if ok {
        fmt.Println("Q:", q)
        fmt.Println("R:", r)
    } else {
        fmt.Println("error")
    }
}

func degree(p []float64) int {
    for d := len(p) - 1; d >= 0; d-- {
        if p[d] != 0 {
            return d
        }
    }
    return -1
}

func pld(nn, dd []float64) (q, r []float64, ok bool) {
    if degree(dd) < 0 {
        return
    }
    nn = append(r, nn...)
    if degree(nn) >= degree(dd) {
        q = make([]float64, degree(nn)-degree(dd)+1)
        for degree(nn) >= degree(dd) {
            d := make([]float64, degree(nn)+1)
            copy(d[degree(nn)-degree(dd):], dd)
            q[degree(nn)-degree(dd)] = nn[degree(nn)] / d[degree(d)]
            for i := range d {
                d[i] *= q[degree(nn)-degree(dd)]
                nn[i] -= d[i]
            }
        }
    }
    return q, nn, true
}
Task: Polynomial long division




Go: package main

import "fmt"

func main() {
    n := []float64{-42, 0, -12, 1}
    d := []float64{-3, 1}
    fmt.Println("N:", n)
    fmt.Println("D:", d)
    q, r, ok := pld(n, d)
    if ok {
        fmt.Println("Q:", q)
        fmt.Println("R:", r)
    } else {
        fmt.Println("error")
    }
}

func degree(p []float64) int {
    for d := len(p) - 1; d >= 0; d-- {
        if p[d] != 0 {
            return d
        }
    }
    return -1
}

func pld(nn, dd []float64) (q, r []float64, ok bool) {
    if degree(dd) < 0 {
        return
    }
    nn = append(r, nn...)
    if degree(nn) >= degree(dd) {
        q = make([]float64, degree(nn)-degree(dd)+1)
        for degree(nn) >= degree(dd) {
            d := make([]float64, degree(nn)+1)
            copy(d[degree(nn)-degree(dd):], dd)
            q[degree(nn)-degree(dd)] = nn[degree(nn)] / d[degree(d)]
            for i := range d {
                d[i] *= q[degree(nn)-degree(dd)]
                nn[i] -= d[i]
            }
        }
    }
    return q, nn, true
}




Python: 

from itertools import izip

def degree(poly):
    while poly and poly[-1] == 0:
        poly.pop()   
    return len(poly)-1

def poly_div(N, D):
    dD = degree(D)
    dN = degree(N)
    if dD < 0: raise ZeroDivisionError
    if dN >= dD:
        q = [0] * dN
        while dN >= dD:
            d = [0]*(dN - dD) + D
            mult = q[dN - dD] = N[-1] / float(d[-1])
            d = [coeff*mult for coeff in d]
            N = [coeffN - coeffd for coeffN, coeffd in izip(N, d)]
            dN = degree(N)
        r = N
    else:
        q = [0]
        r = N
    return q, r

if __name__ == '__main__':
    print "POLYNOMIAL LONG DIVISION"
    N = [-42, 0, -12, 1]
    D = [-3, 1, 0, 0]
    print "  %s / %s =" % (N,D),
    print " %s remainder %s" % poly_div(N, D)
Task: Catamorphism


C++: #include <iostream>
#include <numeric>
#include <functional>
#include <vector>

int main() {
	std::vector<int> nums = { 1, 2, 3, 4, 5 };
	auto nums_added = std::accumulate(std::begin(nums), std::end(nums), 0, std::plus<int>());
	auto nums_other = std::accumulate(std::begin(nums), std::end(nums), 0, [](const int& a, const int& b) {
		return a + 2 * b;
	});
	std::cout << "nums_added: " << nums_added << std::endl;
	std::cout << "nums_other: " << nums_other << std::endl;
}


C#: var nums = Enumerable.Range(1, 10);

int summation = nums.Aggregate((a, b) => a + b);

int product = nums.Aggregate((a, b) => a * b);

string concatenation = nums.Aggregate(String.Empty, (a, b) => a.ToString() + b.ToString());

Console.WriteLine("{0} {1} {2}", summation, product, concatenation);
Task: Catamorphism


C++: #include <iostream>
#include <numeric>
#include <functional>
#include <vector>

int main() {
	std::vector<int> nums = { 1, 2, 3, 4, 5 };
	auto nums_added = std::accumulate(std::begin(nums), std::end(nums), 0, std::plus<int>());
	auto nums_other = std::accumulate(std::begin(nums), std::end(nums), 0, [](const int& a, const int& b) {
		return a + 2 * b;
	});
	std::cout << "nums_added: " << nums_added << std::endl;
	std::cout << "nums_other: " << nums_other << std::endl;
}



Go: package main

import (
	"fmt"
)

func main() {
	n := []int{1, 2, 3, 4, 5}

	fmt.Println(reduce(add, n))
	fmt.Println(reduce(sub, n))
	fmt.Println(reduce(mul, n))
}

func add(a int, b int) int { return a + b }
func sub(a int, b int) int { return a - b }
func mul(a int, b int) int { return a * b }

func reduce(rf func(int, int) int, m []int) int {
	r := m[0]
	for _, v := range m[1:] {
		r = rf(r, v)
	}
	return r
}
Task: Catamorphism


C++: #include <iostream>
#include <numeric>
#include <functional>
#include <vector>

int main() {
	std::vector<int> nums = { 1, 2, 3, 4, 5 };
	auto nums_added = std::accumulate(std::begin(nums), std::end(nums), 0, std::plus<int>());
	auto nums_other = std::accumulate(std::begin(nums), std::end(nums), 0, [](const int& a, const int& b) {
		return a + 2 * b;
	});
	std::cout << "nums_added: " << nums_added << std::endl;
	std::cout << "nums_other: " << nums_other << std::endl;
}




Java: import java.util.stream.Stream;

public class ReduceTask {

    public static void main(String[] args) {
        System.out.println(Stream.of(1, 2, 3, 4, 5).mapToInt(i -> i).sum());
        System.out.println(Stream.of(1, 2, 3, 4, 5).reduce(1, (a, b) -> a * b));
    }
}
Task: Catamorphism


C++: #include <iostream>
#include <numeric>
#include <functional>
#include <vector>

int main() {
	std::vector<int> nums = { 1, 2, 3, 4, 5 };
	auto nums_added = std::accumulate(std::begin(nums), std::end(nums), 0, std::plus<int>());
	auto nums_other = std::accumulate(std::begin(nums), std::end(nums), 0, [](const int& a, const int& b) {
		return a + 2 * b;
	});
	std::cout << "nums_added: " << nums_added << std::endl;
	std::cout << "nums_other: " << nums_other << std::endl;
}






Python: >>> 
>>> from operator import add
>>> listoflists = [['the', 'cat'], ['sat', 'on'], ['the', 'mat']]
>>> help(reduce)
Help on built-in function reduce in module __builtin__:

reduce(...)
    reduce(function, sequence[, initial]) -> value
    
    Apply a function of two arguments cumulatively to the items of a sequence,
    from left to right, so as to reduce the sequence to a single value.
    For example, reduce(lambda x, y: x+y, [1, 2, 3, 4, 5]) calculates
    ((((1+2)+3)+4)+5).  If initial is present, it is placed before the items
    of the sequence in the calculation, and serves as a default when the
    sequence is empty.

>>> reduce(add, listoflists, [])
['the', 'cat', 'sat', 'on', 'the', 'mat']
>>>
Task: Catamorphism


C++: #include <iostream>
#include <numeric>
#include <functional>
#include <vector>

int main() {
	std::vector<int> nums = { 1, 2, 3, 4, 5 };
	auto nums_added = std::accumulate(std::begin(nums), std::end(nums), 0, std::plus<int>());
	auto nums_other = std::accumulate(std::begin(nums), std::end(nums), 0, [](const int& a, const int& b) {
		return a + 2 * b;
	});
	std::cout << "nums_added: " << nums_added << std::endl;
	std::cout << "nums_other: " << nums_other << std::endl;
}







VB: Public Sub reduce()
    s = [{1,2,3,4,5}]
    Debug.Print WorksheetFunction.Sum(s)
    Debug.Print WorksheetFunction.Product(s)
End Sub
Task: Catamorphism



C#: var nums = Enumerable.Range(1, 10);

int summation = nums.Aggregate((a, b) => a + b);

int product = nums.Aggregate((a, b) => a * b);

string concatenation = nums.Aggregate(String.Empty, (a, b) => a.ToString() + b.ToString());

Console.WriteLine("{0} {1} {2}", summation, product, concatenation);


Go: package main

import (
	"fmt"
)

func main() {
	n := []int{1, 2, 3, 4, 5}

	fmt.Println(reduce(add, n))
	fmt.Println(reduce(sub, n))
	fmt.Println(reduce(mul, n))
}

func add(a int, b int) int { return a + b }
func sub(a int, b int) int { return a - b }
func mul(a int, b int) int { return a * b }

func reduce(rf func(int, int) int, m []int) int {
	r := m[0]
	for _, v := range m[1:] {
		r = rf(r, v)
	}
	return r
}
Task: Catamorphism



C#: var nums = Enumerable.Range(1, 10);

int summation = nums.Aggregate((a, b) => a + b);

int product = nums.Aggregate((a, b) => a * b);

string concatenation = nums.Aggregate(String.Empty, (a, b) => a.ToString() + b.ToString());

Console.WriteLine("{0} {1} {2}", summation, product, concatenation);



Java: import java.util.stream.Stream;

public class ReduceTask {

    public static void main(String[] args) {
        System.out.println(Stream.of(1, 2, 3, 4, 5).mapToInt(i -> i).sum());
        System.out.println(Stream.of(1, 2, 3, 4, 5).reduce(1, (a, b) -> a * b));
    }
}