WeixiangYan/CodeTransOcean huggingface dataset:
Task: Square root by hand




Go: package main

import (
    "fmt"
    "math/big"
)

var one = big.NewInt(1)
var ten = big.NewInt(10)
var twenty = big.NewInt(20)
var hundred = big.NewInt(100)

func sqrt(n float64, limit int) {
    if n < 0 {
        log.Fatal("Number cannot be negative")
    }
    count := 0
    for n != math.Trunc(n) {
        n *= 100
        count--
    }
    i := big.NewInt(int64(n))
    j := new(big.Int).Sqrt(i)
    count += len(j.String())
    k := new(big.Int).Set(j)
    d := new(big.Int).Set(j)
    t := new(big.Int)
    digits := 0
    var sb strings.Builder
    for digits < limit {
        sb.WriteString(d.String())
        t.Mul(k, d)
        i.Sub(i, t)
        i.Mul(i, hundred)
        k.Mul(j, twenty)
        d.Set(one)
        for d.Cmp(ten) <= 0 {
            t.Add(k, d)
            t.Mul(t, d)
            if t.Cmp(i) > 0 {
                d.Sub(d, one)
                break
            }
            d.Add(d, one)
        }
        j.Mul(j, ten)
        j.Add(j, d)
        k.Add(k, d)
        digits = digits + 1
    }
    root := strings.TrimRight(sb.String(), "0")
    if len(root) == 0 {
        root = "0"
    }
    if count > 0 {
        root = root[0:count] + "." + root[count:]
    } else if count == 0 {
        root = "0." + root
    } else {
        root = "0." + strings.Repeat("0", -count) + root
    }
    root = strings.TrimSuffix(root, ".")
    fmt.Println(root)
}

func main() {
    numbers := []float64{2, 0.2, 10.89, 625, 0.0001}
    digits := []int{500, 80, 8, 8, 8}
    for i, n := range numbers {
        fmt.Printf("First %d significant digits (at most) of the square root of %g:\n", digits[i], n)
        sqrt(n, digits[i])
        fmt.Println()
    }
}


Java: import java.math.BigInteger;

public class SquareRoot {
    public static final BigInteger ONE_HUNDRED = BigInteger.valueOf(100);
    public static final BigInteger TWENTY = BigInteger.valueOf(20);

    public static void main(String[] args) {
        var i = BigInteger.TWO;
        var j = BigInteger.valueOf((long) Math.floor(Math.sqrt(2.0)));
        var k = j;
        var d = j;
        int n = 500;
        int n0 = n;
        do {
            System.out.print(d);
            i = i.subtract(k.multiply(d)).multiply(ONE_HUNDRED);
            k = TWENTY.multiply(j);
            for (d = BigInteger.ONE; d.compareTo(BigInteger.TEN) <= 0; d = d.add(BigInteger.ONE)) {
                if (k.add(d).multiply(d).compareTo(i) > 0) {
                    d = d.subtract(BigInteger.ONE);
                    break;
                }
            }
            j = j.multiply(BigInteger.TEN).add(d);
            k = k.add(d);
            if (n0 > 0) {
                n--;
            }
        } while (n > 0);
        System.out.println();
    }
}
Task: Reflection_List properties




Go: package main

import (
	"fmt"
	"image"
	"reflect"
)


type t struct {
	X    int
	next *t
}

func main() {
	report(t{})
	report(image.Point{})
}

func report(x interface{}) {
	t := reflect.TypeOf(x)
	n := t.NumField()
	fmt.Printf("Type %v has %d fields:\n", t, n)
	fmt.Println("Name     Type     Exported")
	for i := 0; i < n; i++ {
		f := t.Field(i)
		fmt.Printf("%-8s %-8v %-8t\n",
			f.Name,
			f.Type,
			f.PkgPath == "",
		)
	}
	fmt.Println()
}


Java: import java.lang.reflect.Field;

public class ListFields {
    public int examplePublicField = 42;
    private boolean examplePrivateField = true;
    
    public static void main(String[] args) throws IllegalAccessException {
        ListFields obj = new ListFields();
        Class clazz = obj.getClass();

        System.out.println("All public fields (including inherited):");
        for (Field f : clazz.getFields()) {
            System.out.printf("%s\t%s\n", f, f.get(obj));
        }
        System.out.println();
        System.out.println("All declared fields (excluding inherited):");
        for (Field f : clazz.getDeclaredFields()) {
            System.out.printf("%s\t%s\n", f, f.get(obj));
        }
    }
}
Task: URL parser




Go: package main

import (
	"fmt"
	"log"
	"net"
	"net/url"
)

func main() {
	for _, in := range []string{
		"foo:
		"urn:example:animal:ferret:nose",
		"jdbc:mysql:
		"ftp:
		"http:
		"ldap:
		"mailto:John.Doe@example.com",
		"news:comp.infosystems.www.servers.unix",
		"tel:+1-816-555-1212",
		"telnet:
		"urn:oasis:names:specification:docbook:dtd:xml:4.1.2",

		"ssh:
		"https:
		"http:
	} {
		fmt.Println(in)
		u, err := url.Parse(in)
		if err != nil {
			log.Println(err)
			continue
		}
		if in != u.String() {
			fmt.Printf("Note: reassmebles as %q\n", u)
		}
		printURL(u)
	}
}

func printURL(u *url.URL) {
	fmt.Println("    Scheme:", u.Scheme)
	if u.Opaque != "" {
		fmt.Println("    Opaque:", u.Opaque)
	}
	if u.User != nil {
		fmt.Println("    Username:", u.User.Username())
		if pwd, ok := u.User.Password(); ok {
			fmt.Println("    Password:", pwd)
		}
	}
	if u.Host != "" {
		if host, port, err := net.SplitHostPort(u.Host); err == nil {
			fmt.Println("    Host:", host)
			fmt.Println("    Port:", port)
		} else {
			fmt.Println("    Host:", u.Host)
		}
	}
	if u.Path != "" {
		fmt.Println("    Path:", u.Path)
	}
	if u.RawQuery != "" {
		fmt.Println("    RawQuery:", u.RawQuery)
		m, err := url.ParseQuery(u.RawQuery)
		if err == nil {
			for k, v := range m {
				fmt.Printf("        Key: %q Values: %q\n", k, v)
			}
		}
	}
	if u.Fragment != "" {
		fmt.Println("    Fragment:", u.Fragment)
	}
}


Java: import java.net.URI;
import java.net.URISyntaxException;
public class WebAddressParser{
    public static void main(String[] args){
        parseAddress("foo:
        parseAddress("urn:example:animal:ferret:nose");
    }

    static void parseAddress(String a){
        System.out.println("Parsing " + a);
        try{

            
            URI u = new URI(a);

            System.out.println("\tscheme = " + u.getScheme());
            System.out.println("\tdomain = " + u.getHost());
            System.out.println("\tport = " + (-1==u.getPort()?"default":u.getPort()));
            System.out.println("\tpath = " + (null==u.getPath()?u.getSchemeSpecificPart():u.getPath()));
            System.out.println("\tquery = " + u.getQuery());
            System.out.println("\tfragment = " + u.getFragment());
        }
        catch (URISyntaxException x){
            System.err.println("Oops: " + x);
        }
    }
}
Task: Dynamic variable names




Go: package main

import (
    "bufio"
    "fmt"
    "log"
    "os"
    "strconv"
    "strings"
)

func check(err error) {
    if err != nil {
        log.Fatal(err)
    }
}

func main() {
    scanner := bufio.NewScanner(os.Stdin)
    n := 0
    for n < 1 || n > 5 {
        fmt.Print("How many integer variables do you want to create (max 5) : ")
        scanner.Scan()
        n, _ = strconv.Atoi(scanner.Text())
        check(scanner.Err())
    }
    vars := make(map[string]int)
    fmt.Println("OK, enter the variable names and their values, below")
    for i := 1; i <= n; {
        fmt.Println("\n  Variable", i)
        fmt.Print("    Name  : ")
        scanner.Scan()
        name := scanner.Text()
        check(scanner.Err())
        if _, ok := vars[name]; ok {
            fmt.Println("  Sorry, you've already created a variable of that name, try again")
            continue
        }
        var value int
        var err error
        for {
            fmt.Print("    Value : ")
            scanner.Scan()
            value, err = strconv.Atoi(scanner.Text())
            check(scanner.Err())
            if err != nil {
                fmt.Println("  Not a valid integer, try again")
            } else {
                break
            }
        }
        vars[name] = value
        i++
    }
    fmt.Println("\nEnter q to quit")
    for {
        fmt.Print("\nWhich variable do you want to inspect : ")
        scanner.Scan()
        name := scanner.Text()
        check(scanner.Err())
        if s := strings.ToLower(name); s == "q" {
            return
        }
        v, ok := vars[name]
        if !ok {
            fmt.Println("Sorry there's no variable of that name, try again")
        } else {
            fmt.Println("It's value is", v)
        }
    }
}


Java: public static void main(String... args){
        HashMap<String, Integer> vars = new HashMap<String, Integer>();
        
        
        
        vars.put("Variable name", 3); 
        vars.put("Next variable name", 5);
        Scanner sc = new Scanner(System.in);
        String str = sc.next();
        vars.put(str, sc.nextInt()); 
        
        System.out.println(vars.get("Variable name")); 
        System.out.println(vars.get(str));
}
Task: Data Encryption Standard




Go: package main

import (
    "crypto/des"
    "encoding/hex"
    "fmt"
    "log"
)

func main() {
    key, err := hex.DecodeString("0e329232ea6d0d73")
    if err != nil {
        log.Fatal(err)
    }
    c, err := des.NewCipher(key)
    if err != nil {
        log.Fatal(err)
    }
    src, err := hex.DecodeString("8787878787878787")
    if err != nil {
        log.Fatal(err)
    }
    dst := make([]byte, des.BlockSize)
    c.Encrypt(dst, src)
    fmt.Printf("%x\n", dst)
}


Java: import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;

public class DataEncryptionStandard {
    private static byte[] toHexByteArray(String self) {
        byte[] bytes = new byte[self.length() / 2];
        for (int i = 0; i < bytes.length; ++i) {
            bytes[i] = ((byte) Integer.parseInt(self.substring(i * 2, i * 2 + 2), 16));
        }
        return bytes;
    }

    private static void printHexBytes(byte[] self, String label) {
        System.out.printf("%s: ", label);
        for (byte b : self) {
            int bb = (b >= 0) ? ((int) b) : b + 256;
            String ts = Integer.toString(bb, 16);
            if (ts.length() < 2) {
                ts = "0" + ts;
            }
            System.out.print(ts);
        }
        System.out.println();
    }

    public static void main(String[] args) throws Exception {
        String strKey = "0e329232ea6d0d73";
        byte[] keyBytes = toHexByteArray(strKey);
        SecretKeySpec key = new SecretKeySpec(keyBytes, "DES");
        Cipher encCipher = Cipher.getInstance("DES");
        encCipher.init(Cipher.ENCRYPT_MODE, key);
        String strPlain = "8787878787878787";
        byte[] plainBytes = toHexByteArray(strPlain);
        byte[] encBytes = encCipher.doFinal(plainBytes);
        printHexBytes(encBytes, "Encoded");

        Cipher decCipher = Cipher.getInstance("DES");
        decCipher.init(Cipher.DECRYPT_MODE, key);
        byte[] decBytes = decCipher.doFinal(encBytes);
        printHexBytes(decBytes, "Decoded");
    }
}
Task: Reflection_List methods




Go: package main

import (
	"fmt"
	"image"
	"reflect"
)

type t int 


func (r t) Twice() t       { return r * 2 }
func (r t) Half() t        { return r / 2 }
func (r t) Less(r2 t) bool { return r < r2 }
func (r t) privateMethod() {}

func main() {
	report(t(0))
	report(image.Point{})
}

func report(x interface{}) {
	v := reflect.ValueOf(x)
	t := reflect.TypeOf(x) 
	n := t.NumMethod()
	fmt.Printf("Type %v has %d exported methods:\n", t, n)
	const format = "%-6s %-46s %s\n"
	fmt.Printf(format, "Name", "Method expression", "Method value")
	for i := 0; i < n; i++ {
		fmt.Printf(format,
			t.Method(i).Name,
			t.Method(i).Func.Type(),
			v.Method(i).Type(),
		)
	}
	fmt.Println()
}


Java: import java.lang.reflect.Method;

public class ListMethods {
    public int examplePublicInstanceMethod(char c, double d) {
        return 42;
    }

    private boolean examplePrivateInstanceMethod(String s) {
        return true;
    }
    
    public static void main(String[] args) {
        Class clazz = ListMethods.class;

        System.out.println("All public methods (including inherited):");
        for (Method m : clazz.getMethods()) {
            System.out.println(m);
        }
        System.out.println();
        System.out.println("All declared methods (excluding inherited):");
        for (Method m : clazz.getDeclaredMethods()) {
            System.out.println(m);
        }
    }
}
Task: Send an unknown method call




Go: package main

import (
    "fmt"
    "reflect"
)

type example struct{}


func (example) Foo() int {
    return 42
}

func main() {
    
    var e example
    
    m := reflect.ValueOf(e).MethodByName("Foo")
    
    r := m.Call(nil)
    
    fmt.Println(r[0].Int()) 
}


Java: import java.lang.reflect.Method;

class Example {
  public int foo(int x) {
    return 42 + x;
  }
}

public class Main {
  public static void main(String[] args) throws Exception {
    Object example = new Example();
    String name = "foo";
    Class<?> clazz = example.getClass();
    Method meth = clazz.getMethod(name, int.class);
    Object result = meth.invoke(example, 5); 
    System.out.println(result);        
  }
}
Task: Interactive programming (repl)




Go: package main

import "fmt"

func f(s1, s2, sep string) string {
	return s1 + sep + sep + s2
}

func main() {
	fmt.Println(f("Rosetta", "Code", ":"))
}


Java: public static void main(String[] args) {
    System.out.println(concat("Rosetta", "Code", ":"));
}

public static String concat(String a, String b, String c) {
   return a + c + c + b;
}

Rosetta::Code
Task: Index finite lists of positive integers




Go: package main

import (
    "fmt"
    "math/big"
)

func rank(l []uint) (r big.Int) {
    for _, n := range l {
        r.Lsh(&r, n+1)
        r.SetBit(&r, int(n), 1)
    }
    return
}

func unrank(n big.Int) (l []uint) {
    m := new(big.Int).Set(&n)
    for a := m.BitLen(); a > 0; {
        m.SetBit(m, a-1, 0)
        b := m.BitLen()
        l = append(l, uint(a-b-1))
        a = b
    }
    return
}

func main() {
    var b big.Int
    for i := 0; i <= 10; i++ {
        b.SetInt64(int64(i))
        u := unrank(b)
        r := rank(u)
        fmt.Println(i, u, &r)
    }
    b.SetString("12345678901234567890", 10)
    u := unrank(b)
    r := rank(u)
    fmt.Printf("\n%v\n%d\n%d\n", &b, u, &r)
}


Java: import java.math.BigInteger;
import static java.util.Arrays.stream;
import java.util.*;
import static java.util.stream.Collectors.*;

public class Test3 {
    static BigInteger rank(int[] x) {
        String s = stream(x).mapToObj(String::valueOf).collect(joining("F"));
        return new BigInteger(s, 16);
    }

    static List<BigInteger> unrank(BigInteger n) {
        BigInteger sixteen = BigInteger.valueOf(16);
        String s = "";
        while (!n.equals(BigInteger.ZERO)) {
            s = "0123456789ABCDEF".charAt(n.mod(sixteen).intValue()) + s;
            n = n.divide(sixteen);
        }
        return stream(s.split("F")).map(x -> new BigInteger(x)).collect(toList());
    }

    public static void main(String[] args) {
        int[] s = {1, 2, 3, 10, 100, 987654321};
        System.out.println(Arrays.toString(s));
        System.out.println(rank(s));
        System.out.println(unrank(rank(s)));
    }
}
Task: Make a backup file




Go: package main

import (
    "fmt"
    "io/ioutil"
    "os"
)

func main() {
    fn := "myth"
    bx := ".backup"
    
    var err error
    if tf, err := os.Readlink(fn); err == nil {
        fn = tf
    }
    
    var fi os.FileInfo
    if fi, err = os.Stat(fn); err != nil {
        fmt.Println(err)
        return
    }
    
    if err = os.Rename(fn, fn+bx); err != nil {
        fmt.Println(err)
        return
    }
    
    err = ioutil.WriteFile(fn, []byte("you too!\n"), fi.Mode().Perm())
    if err != nil {
        fmt.Println(err)
    }
}


Java: import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.nio.file.*;
 
public class Backup {
	public static void saveWithBackup(String filename, String... data) 
        throws IOException {
		
		Path file = Paths.get(filename).toRealPath();
		File backFile = new File(filename + ".backup");
		if(!backFile.exists()) {
			
			backFile.createNewFile();
		}
		Path back = Paths.get(filename + ".backup").toRealPath();
		Files.move(file, back, StandardCopyOption.REPLACE_EXISTING);
		try(PrintWriter out = new PrintWriter(file.toFile())){
			for(int i = 0; i < data.length; i++) {
				out.print(data[i]);
				if(i < data.length - 1) {
					out.println();
				}
			}
		}
	}

        public static void main(String[] args) {
		try {
			saveWithBackup("original.txt", "fourth", "fifth", "sixth");
		} catch (IOException e) {
			System.err.println(e);
		}
	} 
}
Task: Generalised floating point addition




Go: package main

import (
    "fmt"
    "math/big"
)

func repeatedAdd(bf *big.Float, times int) *big.Float {
    if times < 2 {
        return bf
    }
    var sum big.Float
    for i := 0; i < times; i++ {
        sum.Add(&sum, bf)
    }
    return &sum
}

func main() {
    s := "12345679"
    t := "123456790"
    e := 63
    var bf, extra big.Float
    for n := -7; n <= 21; n++ {
        bf.SetString(fmt.Sprintf("%se%d", s, e))
        extra.SetString(fmt.Sprintf("1e%d", e))
        bf = *repeatedAdd(&bf, 81)
        bf.Add(&bf, &extra)
        fmt.Printf("%2d : %s\n", n, bf.String())
        s = t + s
        e -= 9
    }
}


Java: import java.math.BigDecimal;

public class GeneralisedFloatingPointAddition {

    public static void main(String[] args) {
        BigDecimal oneExp72 = new BigDecimal("1E72");
        for ( int i = 0 ; i <= 21+7 ; i++ ) {
            String s = "12345679";
            for ( int j = 0 ; j < i ; j++ ) {
                s += "012345679";
            }
            int exp = 63 - 9*i;
            s += "E" + exp;
            BigDecimal num = new BigDecimal(s).multiply(BigDecimal.valueOf(81)).add(new BigDecimal("1E" + exp));
            System.out.printf("Test value (%s) equals computed value: %b.  Computed = %s%n", oneExp72, num.compareTo(oneExp72) == 0 , num);
        }
    }

}
Task: Reverse the gender of a string




Go: package main

import (
    "fmt"
    "strings"
)

func reverseGender(s string) string {
    if strings.Contains(s, "She") {
        return strings.Replace(s, "She", "He", -1)
    } else if strings.Contains(s, "He") {
        return strings.Replace(s, "He", "She", -1)
    }
    return s
}

func main() {
    s := "She was a soul stripper. She took my heart!"
    t := reverseGender(s)
    fmt.Println(t)
    fmt.Println(reverseGender(t))
}


Java: public class ReallyLameTranslationOfJ {

    public static void main(String[] args) {
        String s = "She was a soul stripper. She took my heart!";
        System.out.println(cheapTrick(s));
        System.out.println(cheapTrick(cheapTrick(s)));
    }

    static String cheapTrick(String s) {
        if (s.contains("She"))
            return s.replaceAll("She", "He");
        else if(s.contains("He"))
            return s.replaceAll("He", "She");
        return s;
    }
}
Task: Audio alarm




Go: package main

import (
    "bufio"
    "fmt"
    "log"
    "os"
    "os/exec"
    "strconv"
    "time"
)

func main() {
    scanner := bufio.NewScanner(os.Stdin)
    number := 0
    for number < 1 {
        fmt.Print("Enter number of seconds delay > 0 : ")
        scanner.Scan()
        input := scanner.Text()
        if err := scanner.Err(); err != nil {
            log.Fatal(err)
        }
        number, _ = strconv.Atoi(input)
    }

    filename := ""
    for filename == "" {
        fmt.Print("Enter name of .mp3 file to play (without extension) : ")
        scanner.Scan()
        filename = scanner.Text()
        if err := scanner.Err(); err != nil {
            log.Fatal(err)
        }
    }

    cls := "\033[2J\033[0;0H" 
    fmt.Printf("%sAlarm will sound in %d seconds...", cls, number)
    time.Sleep(time.Duration(number) * time.Second)
    fmt.Printf(cls)
    cmd := exec.Command("play", filename+".mp3")
    if err := cmd.Run(); err != nil {
        log.Fatal(err)
    }
}


Java: import com.sun.javafx.application.PlatformImpl;
import java.io.File;
import java.util.Scanner;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicBoolean;
import javafx.scene.media.Media;
import javafx.scene.media.MediaPlayer;

public class AudioAlarm {

    public static void main(String[] args) throws InterruptedException {
        Scanner input = new Scanner(System.in);

        System.out.print("Enter a number of seconds: ");
        int seconds = Integer.parseInt(input.nextLine());

        System.out.print("Enter a filename (must end with .mp3 or .wav): ");
        String audio = input.nextLine();

        TimeUnit.SECONDS.sleep(seconds);

        Media media = new Media(new File(audio).toURI().toString());
        AtomicBoolean stop = new AtomicBoolean();
        Runnable onEnd = () -> stop.set(true);

        PlatformImpl.startup(() -> {}); 

        MediaPlayer player = new MediaPlayer(media);
        player.setOnEndOfMedia(onEnd);
        player.setOnError(onEnd);
        player.setOnHalted(onEnd);
        player.play();

        while (!stop.get()) {
            Thread.sleep(100);
        }
        System.exit(0); 
    }
}
Task: Generate random numbers without repeating a value




Go: package main

import (
    "fmt"
    "log"
    "math/rand"
    "time"
)




func generate(from, to int64) {
    if to < from || from < 0 {
        log.Fatal("Invalid range.")
    }
    span := to - from + 1
    generated := make([]bool, span) 
    count := span
    for count > 0 {
        n := from + rand.Int63n(span) 
        if !generated[n-from] {
            generated[n-from] = true
            fmt.Printf("%2d ", n)
            count--
        }
    }
    fmt.Println()
}

func main() {
    rand.Seed(time.Now().UnixNano())

    
    for i := 1; i <= 5; i++ {
        generate(1, 20)
    }
}


Java: import java.util.*;

public class RandomShuffle {
    public static void main(String[] args) {
        Random rand = new Random();
        List<Integer> list = new ArrayList<>();
        for (int j = 1; j <= 20; ++j)
            list.add(j);
        Collections.shuffle(list, rand);
        System.out.println(list);
    }
}
Task: History variables




Go: package main

import (
    "fmt"
    "sort"
    "sync"
    "time"
)


type history struct {
    timestamp tsFunc
    hs        []hset
}


type tsFunc func() time.Time


type hset struct {
    int           
    t   time.Time 
}


func newHistory(ts tsFunc) history {
    return history{ts, []hset{{t: ts()}}}
}   
    

func (h history) int() int {
    return h.hs[len(h.hs)-1].int
}
    

func (h *history) set(x int) time.Time {
    t := h.timestamp()
    h.hs = append(h.hs, hset{x, t})
    return t
}


func (h history) dump() {
    for _, hs := range h.hs {
        fmt.Println(hs.t.Format(time.StampNano), hs.int)
    }
}   
    


func (h history) recall(t time.Time) (int,  bool) {
    i := sort.Search(len(h.hs), func(i int) bool {
        return h.hs[i].t.After(t)
    })
    if i > 0 {
        return h.hs[i-1].int, true
    }
    return 0, false
}





func newTimestamper() tsFunc {
    var last time.Time
    return func() time.Time {
        if t := time.Now(); t.After(last) {
            last = t
        } else {
            last.Add(1)
        }
        return last
    }
}



func newProtectedTimestamper() tsFunc {
    var last time.Time
    var m sync.Mutex
    return func() (t time.Time) {
        t = time.Now()
        m.Lock() 
        if t.After(last) {
            last = t
        } else {
            last.Add(1)
            t = last
        }
        m.Unlock()
        return
    }
}

func main() {
    
    ts := newTimestamper()
    
    h := newHistory(ts)
    
    ref := []time.Time{h.set(3), h.set(1), h.set(4)}
    
    fmt.Println("History of variable h:")
    h.dump() 
    
    
    fmt.Println("Recalling values:")
    for _, t := range ref {
        rv, _ := h.recall(t)
        fmt.Println(rv)
    }
}


Java: public class HistoryVariable
{
    private Object value;

    public HistoryVariable(Object v)
    {
        value = v;
    }

    public void update(Object v)
    {
        value = v;
    }

    public Object undo()
    {
        return value;
    }

    @Override
    public String toString()
    {
        return value.toString();
    }

    public void dispose()
    {
    }
}