Instruction
stringlengths
45
106
input_code
stringlengths
1
13.7k
output_code
stringlengths
1
13.7k
Please provide an equivalent version of this PHP code in Go.
$fruits = array( "apple", "banana", "cherry" ); $fruits = array( "apple" => 0, "banana" => 1, "cherry" => 2 ); class Fruit { const APPLE = 0; const BANANA = 1; const CHERRY = 2; } $value = Fruit::APPLE; define("FRUIT_APPLE", 0); define("FRUIT_BANANA", 1); define("FRUIT_CHERRY", 2);
const ( apple = iota banana cherry )
Translate the given PHP code snippet into Go without altering its behavior.
<?php $client = new SoapClient("http://example.com/soap/definition.wsdl"); $result = $client->soapFunc("hello"); $result = $client->anotherSoapFunc(34234); $client = new SoapClient("http://example.com/soap/definition.wsdl"); print_r($client->__getTypes()); print_r($client->__getFunctions()); ?>
package main import ( "fmt" "github.com/tiaguinho/gosoap" "log" ) type CheckVatResponse struct { CountryCode string `xml:"countryCode"` VatNumber string `xml:"vatNumber"` RequestDate string `xml:"requestDate"` Valid string `xml:"valid"` Name string `xml:"name"` Address string `xml:"address"` } var ( rv CheckVatResponse ) func check(err error) { if err != nil { log.Fatal(err) } } func main() { soap, err := gosoap.SoapClient("http: params := gosoap.Params{ "vatNumber": "6388047V", "countryCode": "IE", } err = soap.Call("checkVat", params) check(err) err = soap.Unmarshal(&rv) check(err) fmt.Println("Country Code  : ", rv.CountryCode) fmt.Println("Vat Number  : ", rv.VatNumber) fmt.Println("Request Date  : ", rv.RequestDate) fmt.Println("Valid  : ", rv.Valid) fmt.Println("Name  : ", rv.Name) fmt.Println("Address  : ", rv.Address) }
Write the same code in Go as shown below in PHP.
<?php $client = new SoapClient("http://example.com/soap/definition.wsdl"); $result = $client->soapFunc("hello"); $result = $client->anotherSoapFunc(34234); $client = new SoapClient("http://example.com/soap/definition.wsdl"); print_r($client->__getTypes()); print_r($client->__getFunctions()); ?>
package main import ( "fmt" "github.com/tiaguinho/gosoap" "log" ) type CheckVatResponse struct { CountryCode string `xml:"countryCode"` VatNumber string `xml:"vatNumber"` RequestDate string `xml:"requestDate"` Valid string `xml:"valid"` Name string `xml:"name"` Address string `xml:"address"` } var ( rv CheckVatResponse ) func check(err error) { if err != nil { log.Fatal(err) } } func main() { soap, err := gosoap.SoapClient("http: params := gosoap.Params{ "vatNumber": "6388047V", "countryCode": "IE", } err = soap.Call("checkVat", params) check(err) err = soap.Unmarshal(&rv) check(err) fmt.Println("Country Code  : ", rv.CountryCode) fmt.Println("Vat Number  : ", rv.VatNumber) fmt.Println("Request Date  : ", rv.RequestDate) fmt.Println("Valid  : ", rv.Valid) fmt.Println("Name  : ", rv.Name) fmt.Println("Address  : ", rv.Address) }
Maintain the same structure and functionality when rewriting this code in Go.
<?php function brainfuck_interpret(&$s, &$_s, &$d, &$_d, &$i, &$_i, &$o) { do { switch($s[$_s]) { case '+': $d[$_d] = chr(ord($d[$_d]) + 1); break; case '-': $d[$_d] = chr(ord($d[$_d]) - 1); break; case '>': $_d++; if(!isset($d[$_d])) $d[$_d] = chr(0); break; case '<': $_d--; break; case '.': $o .= $d[$_d]; break; case ',': $d[$_d] = $_i==strlen($i) ? chr(0) : $i[$_i++]; break; case '[': if((int)ord($d[$_d]) == 0) { $brackets = 1; while($brackets && $_s++ < strlen($s)) { if($s[$_s] == '[') $brackets++; else if($s[$_s] == ']') $brackets--; } } else { $pos = $_s++-1; if(brainfuck_interpret($s, $_s, $d, $_d, $i, $_i, $o)) $_s = $pos; } break; case ']': return ((int)ord($d[$_d]) != 0); } } while(++$_s < strlen($s)); } function brainfuck($source, $input='') { $data = array(); $data[0] = chr(0); $data_index = 0; $source_index = 0; $input_index = 0; $output = ''; brainfuck_interpret($source, $source_index, $data, $data_index, $input, $input_index, $output); return $output; } $code = " >++++++++[<+++++++++>-]<.>>+>+>++>[-]+<[>[->+<<++++>]<<]>.+++++++..+++.> >+++++++.<<<[[-]<[-]>]<+++++++++++++++.>>.+++.------.--------.>>+.>++++. "; $inp = '123'; print brainfuck( $code, $inp );
package main import "fmt" func main() { bf(10, `++++++++++[>+>+++>++++>+++++++>++++++++>+++++++++>++ ++++++++>+++++++++++>++++++++++++<<<<<<<<<-]>>>>+.>>> >+..<.<++++++++.>>>+.<<+.<<<<++++.<++.>>>+++++++.>>>.+++. <+++++++.--------.<<<<<+.<+++.---.`) } func bf(dLen int, is string) { ds := make([]byte, dLen) var dp int for ip := 0; ip < len(is); ip++ { switch is[ip] { case '>': dp++ case '<': dp-- case '+': ds[dp]++ case '-': ds[dp]-- case '.': fmt.Printf("%c", ds[dp]) case ',': fmt.Scanf("%c", &ds[dp]) case '[': if ds[dp] == 0 { for nc := 1; nc > 0; { ip++ if is[ip] == '[' { nc++ } else if is[ip] == ']' { nc-- } } } case ']': if ds[dp] != 0 { for nc := 1; nc > 0; { ip-- if is[ip] == ']' { nc++ } else if is[ip] == '[' { nc-- } } } } } }
Please provide an equivalent version of this PHP code in Go.
<?php function brainfuck_interpret(&$s, &$_s, &$d, &$_d, &$i, &$_i, &$o) { do { switch($s[$_s]) { case '+': $d[$_d] = chr(ord($d[$_d]) + 1); break; case '-': $d[$_d] = chr(ord($d[$_d]) - 1); break; case '>': $_d++; if(!isset($d[$_d])) $d[$_d] = chr(0); break; case '<': $_d--; break; case '.': $o .= $d[$_d]; break; case ',': $d[$_d] = $_i==strlen($i) ? chr(0) : $i[$_i++]; break; case '[': if((int)ord($d[$_d]) == 0) { $brackets = 1; while($brackets && $_s++ < strlen($s)) { if($s[$_s] == '[') $brackets++; else if($s[$_s] == ']') $brackets--; } } else { $pos = $_s++-1; if(brainfuck_interpret($s, $_s, $d, $_d, $i, $_i, $o)) $_s = $pos; } break; case ']': return ((int)ord($d[$_d]) != 0); } } while(++$_s < strlen($s)); } function brainfuck($source, $input='') { $data = array(); $data[0] = chr(0); $data_index = 0; $source_index = 0; $input_index = 0; $output = ''; brainfuck_interpret($source, $source_index, $data, $data_index, $input, $input_index, $output); return $output; } $code = " >++++++++[<+++++++++>-]<.>>+>+>++>[-]+<[>[->+<<++++>]<<]>.+++++++..+++.> >+++++++.<<<[[-]<[-]>]<+++++++++++++++.>>.+++.------.--------.>>+.>++++. "; $inp = '123'; print brainfuck( $code, $inp );
package main import "fmt" func main() { bf(10, `++++++++++[>+>+++>++++>+++++++>++++++++>+++++++++>++ ++++++++>+++++++++++>++++++++++++<<<<<<<<<-]>>>>+.>>> >+..<.<++++++++.>>>+.<<+.<<<<++++.<++.>>>+++++++.>>>.+++. <+++++++.--------.<<<<<+.<+++.---.`) } func bf(dLen int, is string) { ds := make([]byte, dLen) var dp int for ip := 0; ip < len(is); ip++ { switch is[ip] { case '>': dp++ case '<': dp-- case '+': ds[dp]++ case '-': ds[dp]-- case '.': fmt.Printf("%c", ds[dp]) case ',': fmt.Scanf("%c", &ds[dp]) case '[': if ds[dp] == 0 { for nc := 1; nc > 0; { ip++ if is[ip] == '[' { nc++ } else if is[ip] == ']' { nc-- } } } case ']': if ds[dp] != 0 { for nc := 1; nc > 0; { ip-- if is[ip] == ']' { nc++ } else if is[ip] == '[' { nc-- } } } } } }
Transform the following PHP implementation into Go, maintaining the same output and logic.
<?php function brainfuck_interpret(&$s, &$_s, &$d, &$_d, &$i, &$_i, &$o) { do { switch($s[$_s]) { case '+': $d[$_d] = chr(ord($d[$_d]) + 1); break; case '-': $d[$_d] = chr(ord($d[$_d]) - 1); break; case '>': $_d++; if(!isset($d[$_d])) $d[$_d] = chr(0); break; case '<': $_d--; break; case '.': $o .= $d[$_d]; break; case ',': $d[$_d] = $_i==strlen($i) ? chr(0) : $i[$_i++]; break; case '[': if((int)ord($d[$_d]) == 0) { $brackets = 1; while($brackets && $_s++ < strlen($s)) { if($s[$_s] == '[') $brackets++; else if($s[$_s] == ']') $brackets--; } } else { $pos = $_s++-1; if(brainfuck_interpret($s, $_s, $d, $_d, $i, $_i, $o)) $_s = $pos; } break; case ']': return ((int)ord($d[$_d]) != 0); } } while(++$_s < strlen($s)); } function brainfuck($source, $input='') { $data = array(); $data[0] = chr(0); $data_index = 0; $source_index = 0; $input_index = 0; $output = ''; brainfuck_interpret($source, $source_index, $data, $data_index, $input, $input_index, $output); return $output; } $code = " >++++++++[<+++++++++>-]<.>>+>+>++>[-]+<[>[->+<<++++>]<<]>.+++++++..+++.> >+++++++.<<<[[-]<[-]>]<+++++++++++++++.>>.+++.------.--------.>>+.>++++. "; $inp = '123'; print brainfuck( $code, $inp );
package main import "fmt" func main() { bf(10, `++++++++++[>+>+++>++++>+++++++>++++++++>+++++++++>++ ++++++++>+++++++++++>++++++++++++<<<<<<<<<-]>>>>+.>>> >+..<.<++++++++.>>>+.<<+.<<<<++++.<++.>>>+++++++.>>>.+++. <+++++++.--------.<<<<<+.<+++.---.`) } func bf(dLen int, is string) { ds := make([]byte, dLen) var dp int for ip := 0; ip < len(is); ip++ { switch is[ip] { case '>': dp++ case '<': dp-- case '+': ds[dp]++ case '-': ds[dp]-- case '.': fmt.Printf("%c", ds[dp]) case ',': fmt.Scanf("%c", &ds[dp]) case '[': if ds[dp] == 0 { for nc := 1; nc > 0; { ip++ if is[ip] == '[' { nc++ } else if is[ip] == ']' { nc-- } } } case ']': if ds[dp] != 0 { for nc := 1; nc > 0; { ip-- if is[ip] == ']' { nc++ } else if is[ip] == '[' { nc-- } } } } } }
Produce a language-to-language conversion: from PHP to Go, same semantics.
<?php function brainfuck_interpret(&$s, &$_s, &$d, &$_d, &$i, &$_i, &$o) { do { switch($s[$_s]) { case '+': $d[$_d] = chr(ord($d[$_d]) + 1); break; case '-': $d[$_d] = chr(ord($d[$_d]) - 1); break; case '>': $_d++; if(!isset($d[$_d])) $d[$_d] = chr(0); break; case '<': $_d--; break; case '.': $o .= $d[$_d]; break; case ',': $d[$_d] = $_i==strlen($i) ? chr(0) : $i[$_i++]; break; case '[': if((int)ord($d[$_d]) == 0) { $brackets = 1; while($brackets && $_s++ < strlen($s)) { if($s[$_s] == '[') $brackets++; else if($s[$_s] == ']') $brackets--; } } else { $pos = $_s++-1; if(brainfuck_interpret($s, $_s, $d, $_d, $i, $_i, $o)) $_s = $pos; } break; case ']': return ((int)ord($d[$_d]) != 0); } } while(++$_s < strlen($s)); } function brainfuck($source, $input='') { $data = array(); $data[0] = chr(0); $data_index = 0; $source_index = 0; $input_index = 0; $output = ''; brainfuck_interpret($source, $source_index, $data, $data_index, $input, $input_index, $output); return $output; } $code = " >++++++++[<+++++++++>-]<.>>+>+>++>[-]+<[>[->+<<++++>]<<]>.+++++++..+++.> >+++++++.<<<[[-]<[-]>]<+++++++++++++++.>>.+++.------.--------.>>+.>++++. "; $inp = '123'; print brainfuck( $code, $inp );
package main import "fmt" func main() { bf(10, `++++++++++[>+>+++>++++>+++++++>++++++++>+++++++++>++ ++++++++>+++++++++++>++++++++++++<<<<<<<<<-]>>>>+.>>> >+..<.<++++++++.>>>+.<<+.<<<<++++.<++.>>>+++++++.>>>.+++. <+++++++.--------.<<<<<+.<+++.---.`) } func bf(dLen int, is string) { ds := make([]byte, dLen) var dp int for ip := 0; ip < len(is); ip++ { switch is[ip] { case '>': dp++ case '<': dp-- case '+': ds[dp]++ case '-': ds[dp]-- case '.': fmt.Printf("%c", ds[dp]) case ',': fmt.Scanf("%c", &ds[dp]) case '[': if ds[dp] == 0 { for nc := 1; nc > 0; { ip++ if is[ip] == '[' { nc++ } else if is[ip] == ']' { nc-- } } } case ']': if ds[dp] != 0 { for nc := 1; nc > 0; { ip-- if is[ip] == ']' { nc++ } else if is[ip] == '[' { nc-- } } } } } }
Ensure the translated Go code behaves exactly like the original PHP snippet.
<?php function meaning_of_life() { return 42; } function main($args) { echo "Main: The meaning of life is " . meaning_of_life() . "\n"; } if (preg_match("/scriptedmain/", $_SERVER["SCRIPT_NAME"])) { main($argv); } ?>
package main import "fmt" func MeaningOfLife() int { return 42 } func libMain() { fmt.Println("The meaning of life is", MeaningOfLife()) }
Convert this PHP block to Go, preserving its control flow and logic.
<?php function meaning_of_life() { return 42; } function main($args) { echo "Main: The meaning of life is " . meaning_of_life() . "\n"; } if (preg_match("/scriptedmain/", $_SERVER["SCRIPT_NAME"])) { main($argv); } ?>
package main import "fmt" func MeaningOfLife() int { return 42 } func libMain() { fmt.Println("The meaning of life is", MeaningOfLife()) }
Convert this PHP block to Go, preserving its control flow and logic.
<?php function meaning_of_life() { return 42; } function main($args) { echo "Main: The meaning of life is " . meaning_of_life() . "\n"; } if (preg_match("/scriptedmain/", $_SERVER["SCRIPT_NAME"])) { main($argv); } ?>
package main import "fmt" func MeaningOfLife() int { return 42 } func libMain() { fmt.Println("The meaning of life is", MeaningOfLife()) }
Can you help me rewrite this code in Go instead of PHP, keeping it the same logically?
<?php function meaning_of_life() { return 42; } function main($args) { echo "Main: The meaning of life is " . meaning_of_life() . "\n"; } if (preg_match("/scriptedmain/", $_SERVER["SCRIPT_NAME"])) { main($argv); } ?>
package main import "fmt" func MeaningOfLife() int { return 42 } func libMain() { fmt.Println("The meaning of life is", MeaningOfLife()) }
Translate the given PHP code snippet into Go without altering its behavior.
<?php foreach(scandir('.') as $fileName){ echo $fileName."\n"; }
package main import ( "fmt" "log" "os" "sort" ) func main() { f, err := os.Open(".") if err != nil { log.Fatal(err) } files, err := f.Readdirnames(0) f.Close() if err != nil { log.Fatal(err) } sort.Strings(files) for _, n := range files { fmt.Println(n) } }
Transform the following PHP implementation into Go, maintaining the same output and logic.
<?php foreach(scandir('.') as $fileName){ echo $fileName."\n"; }
package main import ( "fmt" "log" "os" "sort" ) func main() { f, err := os.Open(".") if err != nil { log.Fatal(err) } files, err := f.Readdirnames(0) f.Close() if err != nil { log.Fatal(err) } sort.Strings(files) for _, n := range files { fmt.Println(n) } }
Port the following code from PHP to Go with equivalent syntax and logic.
<?PHP ECHO <<<REALPROGRAMMERSTHINKINUPPERCASEANDCHEATBYUSINGPRINT JANUARY FEBRUARY MARCH APRIL MAY JUNE MO TU WE TH FR SA SO MO TU WE TH FR SA SO MO TU WE TH FR SA SO MO TU WE TH FR SA SO MO TU WE TH FR SA SO MO TU WE TH FR SA SO 1 2 3 4 5 1 2 1 2 1 2 3 4 5 6 1 2 3 4 1 6 7 8 9 10 11 12 3 4 5 6 7 8 9 3 4 5 6 7 8 9 7 8 9 10 11 12 13 5 6 7 8 9 10 11 2 3 4 5 6 7 8 13 14 15 16 17 18 19 10 11 12 13 14 15 16 10 11 12 13 14 15 16 14 15 16 17 18 19 20 12 13 14 15 16 17 18 9 10 11 12 13 14 15 20 21 22 23 24 25 26 17 18 19 20 21 22 23 17 18 19 20 21 22 23 21 22 23 24 25 26 27 19 20 21 22 23 24 25 16 17 18 19 20 21 22 27 28 29 30 31 24 25 26 27 28 24 25 26 27 28 29 30 28 29 30 26 27 28 29 30 31 23 24 25 26 27 28 29 31 30 JULY AUGUST SEPTEMBER OCTOBER NOVEMBER DECEMBER MO TU WE TH FR SA SO MO TU WE TH FR SA SO MO TU WE TH FR SA SO MO TU WE TH FR SA SO MO TU WE TH FR SA SO MO TU WE TH FR SA SO 1 2 3 4 5 6 1 2 3 1 2 3 4 5 6 7 1 2 3 4 5 1 2 1 2 3 4 5 6 7 7 8 9 10 11 12 13 4 5 6 7 8 9 10 8 9 10 11 12 13 14 6 7 8 9 10 11 12 3 4 5 6 7 8 9 8 9 10 11 12 13 14 14 15 16 17 18 19 20 11 12 13 14 15 16 17 15 16 17 18 19 20 21 13 14 15 16 17 18 19 10 11 12 13 14 15 16 15 16 17 18 19 20 21 21 22 23 24 25 26 27 18 19 20 21 22 23 24 22 23 24 25 26 27 28 20 21 22 23 24 25 26 17 18 19 20 21 22 23 22 23 24 25 26 27 28 28 29 30 31 25 26 27 28 29 30 31 29 30 27 28 29 30 31 24 25 26 27 28 29 30 29 30 31 REALPROGRAMMERSTHINKINUPPERCASEANDCHEATBYUSINGPRINT ; // MAGICAL SEMICOLON
PACKAGE MAIN IMPORT ( "FMT" "TIME" ) CONST PAGEWIDTH = 80 FUNC MAIN() { PRINTCAL(1969) } FUNC PRINTCAL(YEAR INT) { THISDATE := TIME.DATE(YEAR, 1, 1, 1, 1, 1, 1, TIME.UTC) VAR ( DAYARR [12][7][6]INT MONTH, LASTMONTH TIME.MONTH WEEKINMONTH, DAYINMONTH INT ) FOR THISDATE.YEAR() == YEAR { IF MONTH = THISDATE.MONTH(); MONTH != LASTMONTH { WEEKINMONTH = 0 DAYINMONTH = 1 } WEEKDAY := THISDATE.WEEKDAY() IF WEEKDAY == 0 && DAYINMONTH > 1 { WEEKINMONTH++ } DAYARR[INT(MONTH)-1][WEEKDAY][WEEKINMONTH] = THISDATE.DAY() LASTMONTH = MONTH DAYINMONTH++ THISDATE = THISDATE.ADD(TIME.HOUR * 24) } CENTRE := FMT.SPRINTF("%D", PAGEWIDTH/2) FMT.PRINTF("%"+CENTRE+"S\N\N", "[SNOOPY]") CENTRE = FMT.SPRINTF("%D", PAGEWIDTH/2-2) FMT.PRINTF("%"+CENTRE+"D\N\N", YEAR) MONTHS := [12]STRING{ " JANUARY ", " FEBRUARY", " MARCH ", " APRIL ", " MAY ", " JUNE ", " JULY ", " AUGUST ", "SEPTEMBER", " OCTOBER ", " NOVEMBER", " DECEMBER"} DAYS := [7]STRING{"SU", "MO", "TU", "WE", "TH", "FR", "SA"} FOR QTR := 0; QTR < 4; QTR++ { FOR MONTHINQTR := 0; MONTHINQTR < 3; MONTHINQTR++ { FMT.PRINTF(" %S ", MONTHS[QTR*3+MONTHINQTR]) } FMT.PRINTLN() FOR MONTHINQTR := 0; MONTHINQTR < 3; MONTHINQTR++ { FOR DAY := 0; DAY < 7; DAY++ { FMT.PRINTF(" %S", DAYS[DAY]) } FMT.PRINTF(" ") } FMT.PRINTLN() FOR WEEKINMONTH = 0; WEEKINMONTH < 6; WEEKINMONTH++ { FOR MONTHINQTR := 0; MONTHINQTR < 3; MONTHINQTR++ { FOR DAY := 0; DAY < 7; DAY++ { IF DAYARR[QTR*3+MONTHINQTR][DAY][WEEKINMONTH] == 0 { FMT.PRINTF(" ") } ELSE { FMT.PRINTF("%3D", DAYARR[QTR*3+MONTHINQTR][DAY][WEEKINMONTH]) } } FMT.PRINTF(" ") } FMT.PRINTLN() } FMT.PRINTLN() } }
Generate a Go translation of this PHP snippet without changing its computational steps.
<?PHP ECHO <<<REALPROGRAMMERSTHINKINUPPERCASEANDCHEATBYUSINGPRINT JANUARY FEBRUARY MARCH APRIL MAY JUNE MO TU WE TH FR SA SO MO TU WE TH FR SA SO MO TU WE TH FR SA SO MO TU WE TH FR SA SO MO TU WE TH FR SA SO MO TU WE TH FR SA SO 1 2 3 4 5 1 2 1 2 1 2 3 4 5 6 1 2 3 4 1 6 7 8 9 10 11 12 3 4 5 6 7 8 9 3 4 5 6 7 8 9 7 8 9 10 11 12 13 5 6 7 8 9 10 11 2 3 4 5 6 7 8 13 14 15 16 17 18 19 10 11 12 13 14 15 16 10 11 12 13 14 15 16 14 15 16 17 18 19 20 12 13 14 15 16 17 18 9 10 11 12 13 14 15 20 21 22 23 24 25 26 17 18 19 20 21 22 23 17 18 19 20 21 22 23 21 22 23 24 25 26 27 19 20 21 22 23 24 25 16 17 18 19 20 21 22 27 28 29 30 31 24 25 26 27 28 24 25 26 27 28 29 30 28 29 30 26 27 28 29 30 31 23 24 25 26 27 28 29 31 30 JULY AUGUST SEPTEMBER OCTOBER NOVEMBER DECEMBER MO TU WE TH FR SA SO MO TU WE TH FR SA SO MO TU WE TH FR SA SO MO TU WE TH FR SA SO MO TU WE TH FR SA SO MO TU WE TH FR SA SO 1 2 3 4 5 6 1 2 3 1 2 3 4 5 6 7 1 2 3 4 5 1 2 1 2 3 4 5 6 7 7 8 9 10 11 12 13 4 5 6 7 8 9 10 8 9 10 11 12 13 14 6 7 8 9 10 11 12 3 4 5 6 7 8 9 8 9 10 11 12 13 14 14 15 16 17 18 19 20 11 12 13 14 15 16 17 15 16 17 18 19 20 21 13 14 15 16 17 18 19 10 11 12 13 14 15 16 15 16 17 18 19 20 21 21 22 23 24 25 26 27 18 19 20 21 22 23 24 22 23 24 25 26 27 28 20 21 22 23 24 25 26 17 18 19 20 21 22 23 22 23 24 25 26 27 28 28 29 30 31 25 26 27 28 29 30 31 29 30 27 28 29 30 31 24 25 26 27 28 29 30 29 30 31 REALPROGRAMMERSTHINKINUPPERCASEANDCHEATBYUSINGPRINT ; // MAGICAL SEMICOLON
PACKAGE MAIN IMPORT ( "FMT" "TIME" ) CONST PAGEWIDTH = 80 FUNC MAIN() { PRINTCAL(1969) } FUNC PRINTCAL(YEAR INT) { THISDATE := TIME.DATE(YEAR, 1, 1, 1, 1, 1, 1, TIME.UTC) VAR ( DAYARR [12][7][6]INT MONTH, LASTMONTH TIME.MONTH WEEKINMONTH, DAYINMONTH INT ) FOR THISDATE.YEAR() == YEAR { IF MONTH = THISDATE.MONTH(); MONTH != LASTMONTH { WEEKINMONTH = 0 DAYINMONTH = 1 } WEEKDAY := THISDATE.WEEKDAY() IF WEEKDAY == 0 && DAYINMONTH > 1 { WEEKINMONTH++ } DAYARR[INT(MONTH)-1][WEEKDAY][WEEKINMONTH] = THISDATE.DAY() LASTMONTH = MONTH DAYINMONTH++ THISDATE = THISDATE.ADD(TIME.HOUR * 24) } CENTRE := FMT.SPRINTF("%D", PAGEWIDTH/2) FMT.PRINTF("%"+CENTRE+"S\N\N", "[SNOOPY]") CENTRE = FMT.SPRINTF("%D", PAGEWIDTH/2-2) FMT.PRINTF("%"+CENTRE+"D\N\N", YEAR) MONTHS := [12]STRING{ " JANUARY ", " FEBRUARY", " MARCH ", " APRIL ", " MAY ", " JUNE ", " JULY ", " AUGUST ", "SEPTEMBER", " OCTOBER ", " NOVEMBER", " DECEMBER"} DAYS := [7]STRING{"SU", "MO", "TU", "WE", "TH", "FR", "SA"} FOR QTR := 0; QTR < 4; QTR++ { FOR MONTHINQTR := 0; MONTHINQTR < 3; MONTHINQTR++ { FMT.PRINTF(" %S ", MONTHS[QTR*3+MONTHINQTR]) } FMT.PRINTLN() FOR MONTHINQTR := 0; MONTHINQTR < 3; MONTHINQTR++ { FOR DAY := 0; DAY < 7; DAY++ { FMT.PRINTF(" %S", DAYS[DAY]) } FMT.PRINTF(" ") } FMT.PRINTLN() FOR WEEKINMONTH = 0; WEEKINMONTH < 6; WEEKINMONTH++ { FOR MONTHINQTR := 0; MONTHINQTR < 3; MONTHINQTR++ { FOR DAY := 0; DAY < 7; DAY++ { IF DAYARR[QTR*3+MONTHINQTR][DAY][WEEKINMONTH] == 0 { FMT.PRINTF(" ") } ELSE { FMT.PRINTF("%3D", DAYARR[QTR*3+MONTHINQTR][DAY][WEEKINMONTH]) } } FMT.PRINTF(" ") } FMT.PRINTLN() } FMT.PRINTLN() } }
Convert the following code from PHP to Go, ensuring the logic remains intact.
while(1) echo "SPAM\n";
package main import "fmt" func main() { for { fmt.Printf("SPAM\n") } }
Ensure the translated Go code behaves exactly like the original PHP snippet.
while(1) echo "SPAM\n";
package main import "fmt" func main() { for { fmt.Printf("SPAM\n") } }
Convert the following code from PHP to Go, ensuring the logic remains intact.
<?php function symbolTable() { $symbol = array(); for ($c = ord('a') ; $c <= ord('z') ; $c++) { $symbol[$c - ord('a')] = chr($c); } return $symbol; } function mtfEncode($original, $symbol) { $encoded = array(); for ($i = 0 ; $i < strlen($original) ; $i++) { $char = $original[$i]; $position = array_search($char, $symbol); $encoded[] = $position; $mtf = $symbol[$position]; unset($symbol[$position]); array_unshift($symbol, $mtf); } return $encoded; } function mtfDecode($encoded, $symbol) { $decoded = ''; foreach ($encoded AS $position) { $char = $symbol[$position]; $decoded .= $char; unset($symbol[$position]); array_unshift($symbol, $char); } return $decoded; } foreach (array('broood', 'bananaaa', 'hiphophiphop') AS $original) { $encoded = mtfEncode($original, symbolTable()); $decoded = mtfDecode($encoded, symbolTable()); echo $original, ' -> [', implode(',', $encoded), ']', ' -> ', $decoded, ' : ', ($original === $decoded ? 'OK' : 'Error'), PHP_EOL; }
package main import ( "bytes" "fmt" ) type symbolTable string func (symbols symbolTable) encode(s string) []byte { seq := make([]byte, len(s)) pad := []byte(symbols) for i, c := range []byte(s) { x := bytes.IndexByte(pad, c) seq[i] = byte(x) copy(pad[1:], pad[:x]) pad[0] = c } return seq } func (symbols symbolTable) decode(seq []byte) string { chars := make([]byte, len(seq)) pad := []byte(symbols) for i, x := range seq { c := pad[x] chars[i] = c copy(pad[1:], pad[:x]) pad[0] = c } return string(chars) } func main() { m := symbolTable("abcdefghijklmnopqrstuvwxyz") for _, s := range []string{"broood", "bananaaa", "hiphophiphop"} { enc := m.encode(s) dec := m.decode(enc) fmt.Println(s, enc, dec) if dec != s { panic("Whoops!") } } }
Please provide an equivalent version of this PHP code in Go.
<?php function symbolTable() { $symbol = array(); for ($c = ord('a') ; $c <= ord('z') ; $c++) { $symbol[$c - ord('a')] = chr($c); } return $symbol; } function mtfEncode($original, $symbol) { $encoded = array(); for ($i = 0 ; $i < strlen($original) ; $i++) { $char = $original[$i]; $position = array_search($char, $symbol); $encoded[] = $position; $mtf = $symbol[$position]; unset($symbol[$position]); array_unshift($symbol, $mtf); } return $encoded; } function mtfDecode($encoded, $symbol) { $decoded = ''; foreach ($encoded AS $position) { $char = $symbol[$position]; $decoded .= $char; unset($symbol[$position]); array_unshift($symbol, $char); } return $decoded; } foreach (array('broood', 'bananaaa', 'hiphophiphop') AS $original) { $encoded = mtfEncode($original, symbolTable()); $decoded = mtfDecode($encoded, symbolTable()); echo $original, ' -> [', implode(',', $encoded), ']', ' -> ', $decoded, ' : ', ($original === $decoded ? 'OK' : 'Error'), PHP_EOL; }
package main import ( "bytes" "fmt" ) type symbolTable string func (symbols symbolTable) encode(s string) []byte { seq := make([]byte, len(s)) pad := []byte(symbols) for i, c := range []byte(s) { x := bytes.IndexByte(pad, c) seq[i] = byte(x) copy(pad[1:], pad[:x]) pad[0] = c } return seq } func (symbols symbolTable) decode(seq []byte) string { chars := make([]byte, len(seq)) pad := []byte(symbols) for i, x := range seq { c := pad[x] chars[i] = c copy(pad[1:], pad[:x]) pad[0] = c } return string(chars) } func main() { m := symbolTable("abcdefghijklmnopqrstuvwxyz") for _, s := range []string{"broood", "bananaaa", "hiphophiphop"} { enc := m.encode(s) dec := m.decode(enc) fmt.Println(s, enc, dec) if dec != s { panic("Whoops!") } } }
Write the same code in Go as shown below in PHP.
<?php $l = ldap_connect('ldap.example.com'); ldap_set_option($l, LDAP_OPT_PROTOCOL_VERSION, 3); ldap_set_option($l, LDAP_OPT_REFERRALS, false); $bind = ldap_bind($l, 'me@example.com', 'password'); $base = 'dc=example, dc=com'; $criteria = '(&(objectClass=user)(sAMAccountName=username))'; $attributes = array('displayName', 'company'); $search = ldap_search($l, $base, $criteria, $attributes); $entries = ldap_get_entries($l, $search); var_dump($entries);
package main import ( "log" "github.com/jtblin/go-ldap-client" ) func main() { client := &ldap.LDAPClient{ Base: "dc=example,dc=com", Host: "ldap.example.com", Port: 389, GroupFilter: "(memberUid=%s)", } defer client.Close() err := client.Connect() if err != nil { log.Fatalf("Failed to connect : %+v", err) } groups, err := client.GetGroupsOfUser("username") if err != nil { log.Fatalf("Error getting groups for user %s: %+v", "username", err) } log.Printf("Groups: %+v", groups) }
Change the following PHP code into Go without altering its purpose.
<?php $l = ldap_connect('ldap.example.com'); ldap_set_option($l, LDAP_OPT_PROTOCOL_VERSION, 3); ldap_set_option($l, LDAP_OPT_REFERRALS, false); $bind = ldap_bind($l, 'me@example.com', 'password'); $base = 'dc=example, dc=com'; $criteria = '(&(objectClass=user)(sAMAccountName=username))'; $attributes = array('displayName', 'company'); $search = ldap_search($l, $base, $criteria, $attributes); $entries = ldap_get_entries($l, $search); var_dump($entries);
package main import ( "log" "github.com/jtblin/go-ldap-client" ) func main() { client := &ldap.LDAPClient{ Base: "dc=example,dc=com", Host: "ldap.example.com", Port: 389, GroupFilter: "(memberUid=%s)", } defer client.Close() err := client.Connect() if err != nil { log.Fatalf("Failed to connect : %+v", err) } groups, err := client.GetGroupsOfUser("username") if err != nil { log.Fatalf("Error getting groups for user %s: %+v", "username", err) } log.Printf("Groups: %+v", groups) }
Write a version of this PHP function in Go with identical behavior.
@exec($command,$output); echo nl2br($output);
package main import ( "log" "os" "os/exec" ) func main() { cmd := exec.Command("ls", "-l") cmd.Stdout = os.Stdout cmd.Stderr = os.Stderr if err := cmd.Run(); err != nil { log.Fatal(err) } }
Port the following code from PHP to Go with equivalent syntax and logic.
@exec($command,$output); echo nl2br($output);
package main import ( "log" "os" "os/exec" ) func main() { cmd := exec.Command("ls", "-l") cmd.Stdout = os.Stdout cmd.Stderr = os.Stderr if err := cmd.Run(); err != nil { log.Fatal(err) } }
Port the provided PHP code into Go while preserving the original functionality.
libxml_use_internal_errors(true); $xml = new DOMDocument(); $xml->load('shiporder.xml'); if (!$xml->schemaValidate('shiporder.xsd')) { var_dump(libxml_get_errors()); exit; } else { echo 'success'; }
package main import ( "fmt" "github.com/lestrrat-go/libxml2" "github.com/lestrrat-go/libxml2/xsd" "io/ioutil" "log" "os" ) func check(err error) { if err != nil { log.Fatal(err) } } func main() { xsdfile := "shiporder.xsd" f, err := os.Open(xsdfile) check(err) defer f.Close() buf, err := ioutil.ReadAll(f) check(err) s, err := xsd.Parse(buf) check(err) defer s.Free() xmlfile := "shiporder.xml" f2, err := os.Open(xmlfile) check(err) defer f2.Close() buf2, err := ioutil.ReadAll(f2) check(err) d, err := libxml2.Parse(buf2) check(err) if err := s.Validate(d); err != nil { for _, e := range err.(xsd.SchemaValidationError).Errors() { log.Printf("error: %s", e.Error()) } return } fmt.Println("Validation of", xmlfile, "against", xsdfile, "successful!") }
Generate an equivalent Go version of this PHP code.
libxml_use_internal_errors(true); $xml = new DOMDocument(); $xml->load('shiporder.xml'); if (!$xml->schemaValidate('shiporder.xsd')) { var_dump(libxml_get_errors()); exit; } else { echo 'success'; }
package main import ( "fmt" "github.com/lestrrat-go/libxml2" "github.com/lestrrat-go/libxml2/xsd" "io/ioutil" "log" "os" ) func check(err error) { if err != nil { log.Fatal(err) } } func main() { xsdfile := "shiporder.xsd" f, err := os.Open(xsdfile) check(err) defer f.Close() buf, err := ioutil.ReadAll(f) check(err) s, err := xsd.Parse(buf) check(err) defer s.Free() xmlfile := "shiporder.xml" f2, err := os.Open(xmlfile) check(err) defer f2.Close() buf2, err := ioutil.ReadAll(f2) check(err) d, err := libxml2.Parse(buf2) check(err) if err := s.Validate(d); err != nil { for _, e := range err.(xsd.SchemaValidationError).Errors() { log.Printf("error: %s", e.Error()) } return } fmt.Println("Validation of", xmlfile, "against", xsdfile, "successful!") }
Produce a functionally identical Go code for the snippet given in PHP.
<?php class Node { public $val; public $back = NULL; } function lis($n) { $pileTops = array(); foreach ($n as $x) { $low = 0; $high = count($pileTops)-1; while ($low <= $high) { $mid = (int)(($low + $high) / 2); if ($pileTops[$mid]->val >= $x) $high = $mid - 1; else $low = $mid + 1; } $i = $low; $node = new Node(); $node->val = $x; if ($i != 0) $node->back = $pileTops[$i-1]; $pileTops[$i] = $node; } $result = array(); for ($node = count($pileTops) ? $pileTops[count($pileTops)-1] : NULL; $node != NULL; $node = $node->back) $result[] = $node->val; return array_reverse($result); } print_r(lis(array(3, 2, 6, 4, 5, 1))); print_r(lis(array(0, 8, 4, 12, 2, 10, 6, 14, 1, 9, 5, 13, 3, 11, 7, 15))); ?>
package main import ( "fmt" "sort" ) type Node struct { val int back *Node } func lis (n []int) (result []int) { var pileTops []*Node for _, x := range n { j := sort.Search(len(pileTops), func (i int) bool { return pileTops[i].val >= x }) node := &Node{ x, nil } if j != 0 { node.back = pileTops[j-1] } if j != len(pileTops) { pileTops[j] = node } else { pileTops = append(pileTops, node) } } if len(pileTops) == 0 { return []int{} } for node := pileTops[len(pileTops)-1]; node != nil; node = node.back { result = append(result, node.val) } for i := 0; i < len(result)/2; i++ { result[i], result[len(result)-i-1] = result[len(result)-i-1], result[i] } return } func main() { for _, d := range [][]int{{3, 2, 6, 4, 5, 1}, {0, 8, 4, 12, 2, 10, 6, 14, 1, 9, 5, 13, 3, 11, 7, 15}} { fmt.Printf("an L.I.S. of %v is %v\n", d, lis(d)) } }
Maintain the same structure and functionality when rewriting this code in Go.
<?php class Node { public $val; public $back = NULL; } function lis($n) { $pileTops = array(); foreach ($n as $x) { $low = 0; $high = count($pileTops)-1; while ($low <= $high) { $mid = (int)(($low + $high) / 2); if ($pileTops[$mid]->val >= $x) $high = $mid - 1; else $low = $mid + 1; } $i = $low; $node = new Node(); $node->val = $x; if ($i != 0) $node->back = $pileTops[$i-1]; $pileTops[$i] = $node; } $result = array(); for ($node = count($pileTops) ? $pileTops[count($pileTops)-1] : NULL; $node != NULL; $node = $node->back) $result[] = $node->val; return array_reverse($result); } print_r(lis(array(3, 2, 6, 4, 5, 1))); print_r(lis(array(0, 8, 4, 12, 2, 10, 6, 14, 1, 9, 5, 13, 3, 11, 7, 15))); ?>
package main import ( "fmt" "sort" ) type Node struct { val int back *Node } func lis (n []int) (result []int) { var pileTops []*Node for _, x := range n { j := sort.Search(len(pileTops), func (i int) bool { return pileTops[i].val >= x }) node := &Node{ x, nil } if j != 0 { node.back = pileTops[j-1] } if j != len(pileTops) { pileTops[j] = node } else { pileTops = append(pileTops, node) } } if len(pileTops) == 0 { return []int{} } for node := pileTops[len(pileTops)-1]; node != nil; node = node.back { result = append(result, node.val) } for i := 0; i < len(result)/2; i++ { result[i], result[len(result)-i-1] = result[len(result)-i-1], result[i] } return } func main() { for _, d := range [][]int{{3, 2, 6, 4, 5, 1}, {0, 8, 4, 12, 2, 10, 6, 14, 1, 9, 5, 13, 3, 11, 7, 15}} { fmt.Printf("an L.I.S. of %v is %v\n", d, lis(d)) } }
Produce a functionally identical Go code for the snippet given in PHP.
function getitem($s,$depth=0) { $out = ['']; while ($s) { $c = $s[0]; if ($depth && ($c == ',' || $c == '}')) { return [$out, $s]; } if ($c == '{') { $x = getgroup(substr($s, 1), $depth + 1); if($x) { $tmp = []; foreach($out as $a) { foreach($x[0] as $b) { $tmp[] = $a . $b; } } $out = $tmp; $s = $x[1]; continue; } } if ($c == '\\' && strlen($s) > 1) { list($s, $c) = [substr($s, 1), ($c . $s[1])]; } $tmp = []; foreach($out as $a) { $tmp[] = $a . $c; } $out = $tmp; $s = substr($s, 1); } return [$out, $s]; } function getgroup($s,$depth) { list($out, $comma) = [[], false]; while ($s) { list($g, $s) = getitem($s, $depth); if (!$s) { break; } $out = array_merge($out, $g); if ($s[0] == '}') { if ($comma) { return [$out, substr($s, 1)]; } $tmp = []; foreach($out as $a) { $tmp[] = '{' . $a . '}'; } return [$tmp, substr($s, 1)]; } if ($s[0] == ',') { list($comma, $s) = [true, substr($s, 1)]; } } return null; } $lines = <<< 'END' ~/{Downloads,Pictures}/*.{jpg,gif,png} It{{em,alic}iz,erat}e{d,}, please. {,{,gotta have{ ,\, again\, }}more }cowbell! {}} some }{,{\\{ edge, edge} \,}{ cases, {here} \\\\\} END; foreach( explode("\n", $lines) as $line ) { printf("\n%s\n", $line); foreach( getitem($line)[0] as $expansion ) { printf(" %s\n", $expansion); } }
package expand type Expander interface { Expand() []string } type Text string func (t Text) Expand() []string { return []string{string(t)} } type Alternation []Expander func (alt Alternation) Expand() []string { var out []string for _, e := range alt { out = append(out, e.Expand()...) } return out } type Sequence []Expander func (seq Sequence) Expand() []string { if len(seq) == 0 { return nil } out := seq[0].Expand() for _, e := range seq[1:] { out = combine(out, e.Expand()) } return out } func combine(al, bl []string) []string { out := make([]string, 0, len(al)*len(bl)) for _, a := range al { for _, b := range bl { out = append(out, a+b) } } return out } const ( escape = '\\' altStart = '{' altEnd = '}' altSep = ',' ) type piT struct{ pos, cnt, depth int } type Brace string func Expand(s string) []string { return Brace(s).Expand() } func (b Brace) Expand() []string { return b.Expander().Expand() } func (b Brace) Expander() Expander { s := string(b) var posInfo []piT var stack []int removePosInfo := func(i int) { end := len(posInfo) - 1 copy(posInfo[i:end], posInfo[i+1:]) posInfo = posInfo[:end] } inEscape := false for i, r := range s { if inEscape { inEscape = false continue } switch r { case escape: inEscape = true case altStart: stack = append(stack, len(posInfo)) posInfo = append(posInfo, piT{i, 0, len(stack)}) case altEnd: if len(stack) == 0 { continue } si := len(stack) - 1 pi := stack[si] if posInfo[pi].cnt == 0 { removePosInfo(pi) for pi < len(posInfo) { if posInfo[pi].depth == len(stack) { removePosInfo(pi) } else { pi++ } } } else { posInfo = append(posInfo, piT{i, -2, len(stack)}) } stack = stack[:si] case altSep: if len(stack) == 0 { continue } posInfo = append(posInfo, piT{i, -1, len(stack)}) posInfo[stack[len(stack)-1]].cnt++ } } for len(stack) > 0 { si := len(stack) - 1 pi := stack[si] depth := posInfo[pi].depth removePosInfo(pi) for pi < len(posInfo) { if posInfo[pi].depth == depth { removePosInfo(pi) } else { pi++ } } stack = stack[:si] } return buildExp(s, 0, posInfo) } func buildExp(s string, off int, info []piT) Expander { if len(info) == 0 { return Text(s) } var seq Sequence i := 0 var dj, j, depth int for dk, piK := range info { k := piK.pos - off switch s[k] { case altStart: if depth == 0 { dj = dk j = k depth = piK.depth } case altEnd: if piK.depth != depth { continue } if j > i { seq = append(seq, Text(s[i:j])) } alt := buildAlt(s[j+1:k], depth, j+1+off, info[dj+1:dk]) seq = append(seq, alt) i = k + 1 depth = 0 } } if j := len(s); j > i { seq = append(seq, Text(s[i:j])) } if len(seq) == 1 { return seq[0] } return seq } func buildAlt(s string, depth, off int, info []piT) Alternation { var alt Alternation i := 0 var di int for dk, piK := range info { if piK.depth != depth { continue } if k := piK.pos - off; s[k] == altSep { sub := buildExp(s[i:k], i+off, info[di:dk]) alt = append(alt, sub) i = k + 1 di = dk + 1 } } sub := buildExp(s[i:], i+off, info[di:]) alt = append(alt, sub) return alt }
Convert the following code from PHP to Go, ensuring the logic remains intact.
function getitem($s,$depth=0) { $out = ['']; while ($s) { $c = $s[0]; if ($depth && ($c == ',' || $c == '}')) { return [$out, $s]; } if ($c == '{') { $x = getgroup(substr($s, 1), $depth + 1); if($x) { $tmp = []; foreach($out as $a) { foreach($x[0] as $b) { $tmp[] = $a . $b; } } $out = $tmp; $s = $x[1]; continue; } } if ($c == '\\' && strlen($s) > 1) { list($s, $c) = [substr($s, 1), ($c . $s[1])]; } $tmp = []; foreach($out as $a) { $tmp[] = $a . $c; } $out = $tmp; $s = substr($s, 1); } return [$out, $s]; } function getgroup($s,$depth) { list($out, $comma) = [[], false]; while ($s) { list($g, $s) = getitem($s, $depth); if (!$s) { break; } $out = array_merge($out, $g); if ($s[0] == '}') { if ($comma) { return [$out, substr($s, 1)]; } $tmp = []; foreach($out as $a) { $tmp[] = '{' . $a . '}'; } return [$tmp, substr($s, 1)]; } if ($s[0] == ',') { list($comma, $s) = [true, substr($s, 1)]; } } return null; } $lines = <<< 'END' ~/{Downloads,Pictures}/*.{jpg,gif,png} It{{em,alic}iz,erat}e{d,}, please. {,{,gotta have{ ,\, again\, }}more }cowbell! {}} some }{,{\\{ edge, edge} \,}{ cases, {here} \\\\\} END; foreach( explode("\n", $lines) as $line ) { printf("\n%s\n", $line); foreach( getitem($line)[0] as $expansion ) { printf(" %s\n", $expansion); } }
package expand type Expander interface { Expand() []string } type Text string func (t Text) Expand() []string { return []string{string(t)} } type Alternation []Expander func (alt Alternation) Expand() []string { var out []string for _, e := range alt { out = append(out, e.Expand()...) } return out } type Sequence []Expander func (seq Sequence) Expand() []string { if len(seq) == 0 { return nil } out := seq[0].Expand() for _, e := range seq[1:] { out = combine(out, e.Expand()) } return out } func combine(al, bl []string) []string { out := make([]string, 0, len(al)*len(bl)) for _, a := range al { for _, b := range bl { out = append(out, a+b) } } return out } const ( escape = '\\' altStart = '{' altEnd = '}' altSep = ',' ) type piT struct{ pos, cnt, depth int } type Brace string func Expand(s string) []string { return Brace(s).Expand() } func (b Brace) Expand() []string { return b.Expander().Expand() } func (b Brace) Expander() Expander { s := string(b) var posInfo []piT var stack []int removePosInfo := func(i int) { end := len(posInfo) - 1 copy(posInfo[i:end], posInfo[i+1:]) posInfo = posInfo[:end] } inEscape := false for i, r := range s { if inEscape { inEscape = false continue } switch r { case escape: inEscape = true case altStart: stack = append(stack, len(posInfo)) posInfo = append(posInfo, piT{i, 0, len(stack)}) case altEnd: if len(stack) == 0 { continue } si := len(stack) - 1 pi := stack[si] if posInfo[pi].cnt == 0 { removePosInfo(pi) for pi < len(posInfo) { if posInfo[pi].depth == len(stack) { removePosInfo(pi) } else { pi++ } } } else { posInfo = append(posInfo, piT{i, -2, len(stack)}) } stack = stack[:si] case altSep: if len(stack) == 0 { continue } posInfo = append(posInfo, piT{i, -1, len(stack)}) posInfo[stack[len(stack)-1]].cnt++ } } for len(stack) > 0 { si := len(stack) - 1 pi := stack[si] depth := posInfo[pi].depth removePosInfo(pi) for pi < len(posInfo) { if posInfo[pi].depth == depth { removePosInfo(pi) } else { pi++ } } stack = stack[:si] } return buildExp(s, 0, posInfo) } func buildExp(s string, off int, info []piT) Expander { if len(info) == 0 { return Text(s) } var seq Sequence i := 0 var dj, j, depth int for dk, piK := range info { k := piK.pos - off switch s[k] { case altStart: if depth == 0 { dj = dk j = k depth = piK.depth } case altEnd: if piK.depth != depth { continue } if j > i { seq = append(seq, Text(s[i:j])) } alt := buildAlt(s[j+1:k], depth, j+1+off, info[dj+1:dk]) seq = append(seq, alt) i = k + 1 depth = 0 } } if j := len(s); j > i { seq = append(seq, Text(s[i:j])) } if len(seq) == 1 { return seq[0] } return seq } func buildAlt(s string, depth, off int, info []piT) Alternation { var alt Alternation i := 0 var di int for dk, piK := range info { if piK.depth != depth { continue } if k := piK.pos - off; s[k] == altSep { sub := buildExp(s[i:k], i+off, info[di:dk]) alt = append(alt, sub) i = k + 1 di = dk + 1 } } sub := buildExp(s[i:], i+off, info[di:]) alt = append(alt, sub) return alt }
Write the same code in Go as shown below in PHP.
<?php function is_describing($number) { foreach (str_split((int) $number) as $place => $value) { if (substr_count($number, $place) != $value) { return false; } } return true; } for ($i = 0; $i <= 50000000; $i += 10) { if (is_describing($i)) { echo $i . PHP_EOL; } } ?>
package main import ( "fmt" "strconv" "strings" ) func sdn(n int64) bool { if n >= 1e10 { return false } s := strconv.FormatInt(n, 10) for d, p := range s { if int(p)-'0' != strings.Count(s, strconv.Itoa(d)) { return false } } return true } func main() { for n := int64(0); n < 1e10; n++ { if sdn(n) { fmt.Println(n) } } }
Rewrite this program in Go while keeping its functionality equivalent to the PHP version.
<?php function is_describing($number) { foreach (str_split((int) $number) as $place => $value) { if (substr_count($number, $place) != $value) { return false; } } return true; } for ($i = 0; $i <= 50000000; $i += 10) { if (is_describing($i)) { echo $i . PHP_EOL; } } ?>
package main import ( "fmt" "strconv" "strings" ) func sdn(n int64) bool { if n >= 1e10 { return false } s := strconv.FormatInt(n, 10) for d, p := range s { if int(p)-'0' != strings.Count(s, strconv.Itoa(d)) { return false } } return true } func main() { for n := int64(0); n < 1e10; n++ { if sdn(n) { fmt.Println(n) } } }
Port the provided PHP code into Go while preserving the original functionality.
<?php function invmod($a,$n){ if ($n < 0) $n = -$n; if ($a < 0) $a = $n - (-$a % $n); $t = 0; $nt = 1; $r = $n; $nr = $a % $n; while ($nr != 0) { $quot= intval($r/$nr); $tmp = $nt; $nt = $t - $quot*$nt; $t = $tmp; $tmp = $nr; $nr = $r - $quot*$nr; $r = $tmp; } if ($r > 1) return -1; if ($t < 0) $t += $n; return $t; } printf("%d\n", invmod(42, 2017)); ?>
package main import ( "fmt" "math/big" ) func main() { a := big.NewInt(42) m := big.NewInt(2017) k := new(big.Int).ModInverse(a, m) fmt.Println(k) }
Port the provided PHP code into Go while preserving the original functionality.
<?php function invmod($a,$n){ if ($n < 0) $n = -$n; if ($a < 0) $a = $n - (-$a % $n); $t = 0; $nt = 1; $r = $n; $nr = $a % $n; while ($nr != 0) { $quot= intval($r/$nr); $tmp = $nt; $nt = $t - $quot*$nt; $t = $tmp; $tmp = $nr; $nr = $r - $quot*$nr; $r = $tmp; } if ($r > 1) return -1; if ($t < 0) $t += $n; return $t; } printf("%d\n", invmod(42, 2017)); ?>
package main import ( "fmt" "math/big" ) func main() { a := big.NewInt(42) m := big.NewInt(2017) k := new(big.Int).ModInverse(a, m) fmt.Println(k) }
Please provide an equivalent version of this PHP code in Go.
<?php $socket = socket_create(AF_INET, SOCK_STREAM, 0) or die('Failed to create socket!'); socket_bind($socket, 0, 8080); socket_listen($socket); $msg = '<html><head><title>Goodbye, world!</title></head><body>Goodbye, world!</body></html>'; for (;;) { if ($client = @socket_accept($socket)) { socket_write($client, "HTTP/1.1 200 OK\r\n" . "Content-length: " . strlen($msg) . "\r\n" . "Content-Type: text/html; charset=UTF-8\r\n\r\n" . $msg); } else usleep(100000); // limits CPU usage by sleeping after doing every request } ?>
package main import ( "fmt" "log" "net/http" ) func main() { http.HandleFunc("/", func(w http.ResponseWriter, req *http.Request) { fmt.Fprintln(w, "Goodbye, World!") }) log.Fatal(http.ListenAndServe(":8080", nil)) }
Maintain the same structure and functionality when rewriting this code in Go.
<?php $socket = socket_create(AF_INET, SOCK_STREAM, 0) or die('Failed to create socket!'); socket_bind($socket, 0, 8080); socket_listen($socket); $msg = '<html><head><title>Goodbye, world!</title></head><body>Goodbye, world!</body></html>'; for (;;) { if ($client = @socket_accept($socket)) { socket_write($client, "HTTP/1.1 200 OK\r\n" . "Content-length: " . strlen($msg) . "\r\n" . "Content-Type: text/html; charset=UTF-8\r\n\r\n" . $msg); } else usleep(100000); // limits CPU usage by sleeping after doing every request } ?>
package main import ( "fmt" "log" "net/http" ) func main() { http.HandleFunc("/", func(w http.ResponseWriter, req *http.Request) { fmt.Fprintln(w, "Goodbye, World!") }) log.Fatal(http.ListenAndServe(":8080", nil)) }
Convert this PHP block to Go, preserving its control flow and logic.
<? $image = imagecreate(200, 200); imagecolorallocate($image, 255, 255, 255); $color = imagecolorallocate($image, 255, 0, 0); cubicbezier($image, $color, 160, 10, 10, 40, 30, 160, 150, 110); imagepng($image); function cubicbezier($img, $col, $x0, $y0, $x1, $y1, $x2, $y2, $x3, $y3, $n = 20) { $pts = array(); for($i = 0; $i <= $n; $i++) { $t = $i / $n; $t1 = 1 - $t; $a = pow($t1, 3); $b = 3 * $t * pow($t1, 2); $c = 3 * pow($t, 2) * $t1; $d = pow($t, 3); $x = round($a * $x0 + $b * $x1 + $c * $x2 + $d * $x3); $y = round($a * $y0 + $b * $y1 + $c * $y2 + $d * $y3); $pts[$i] = array($x, $y); } for($i = 0; $i < $n; $i++) { imageline($img, $pts[$i][0], $pts[$i][1], $pts[$i+1][0], $pts[$i+1][1], $col); } }
package raster const b3Seg = 30 func (b *Bitmap) Bézier3(x1, y1, x2, y2, x3, y3, x4, y4 int, p Pixel) { var px, py [b3Seg + 1]int fx1, fy1 := float64(x1), float64(y1) fx2, fy2 := float64(x2), float64(y2) fx3, fy3 := float64(x3), float64(y3) fx4, fy4 := float64(x4), float64(y4) for i := range px { d := float64(i) / b3Seg a := 1 - d b, c := a * a, d * d a, b, c, d = a*b, 3*b*d, 3*a*c, c*d px[i] = int(a*fx1 + b*fx2 + c*fx3 + d*fx4) py[i] = int(a*fy1 + b*fy2 + c*fy3 + d*fy4) } x0, y0 := px[0], py[0] for i := 1; i <= b3Seg; i++ { x1, y1 := px[i], py[i] b.Line(x0, y0, x1, y1, p) x0, y0 = x1, y1 } } func (b *Bitmap) Bézier3Rgb(x1, y1, x2, y2, x3, y3, x4, y4 int, c Rgb) { b.Bézier3(x1, y1, x2, y2, x3, y3, x4, y4, c.Pixel()) }
Maintain the same structure and functionality when rewriting this code in Go.
<? $image = imagecreate(200, 200); imagecolorallocate($image, 255, 255, 255); $color = imagecolorallocate($image, 255, 0, 0); cubicbezier($image, $color, 160, 10, 10, 40, 30, 160, 150, 110); imagepng($image); function cubicbezier($img, $col, $x0, $y0, $x1, $y1, $x2, $y2, $x3, $y3, $n = 20) { $pts = array(); for($i = 0; $i <= $n; $i++) { $t = $i / $n; $t1 = 1 - $t; $a = pow($t1, 3); $b = 3 * $t * pow($t1, 2); $c = 3 * pow($t, 2) * $t1; $d = pow($t, 3); $x = round($a * $x0 + $b * $x1 + $c * $x2 + $d * $x3); $y = round($a * $y0 + $b * $y1 + $c * $y2 + $d * $y3); $pts[$i] = array($x, $y); } for($i = 0; $i < $n; $i++) { imageline($img, $pts[$i][0], $pts[$i][1], $pts[$i+1][0], $pts[$i+1][1], $col); } }
package raster const b3Seg = 30 func (b *Bitmap) Bézier3(x1, y1, x2, y2, x3, y3, x4, y4 int, p Pixel) { var px, py [b3Seg + 1]int fx1, fy1 := float64(x1), float64(y1) fx2, fy2 := float64(x2), float64(y2) fx3, fy3 := float64(x3), float64(y3) fx4, fy4 := float64(x4), float64(y4) for i := range px { d := float64(i) / b3Seg a := 1 - d b, c := a * a, d * d a, b, c, d = a*b, 3*b*d, 3*a*c, c*d px[i] = int(a*fx1 + b*fx2 + c*fx3 + d*fx4) py[i] = int(a*fy1 + b*fy2 + c*fy3 + d*fy4) } x0, y0 := px[0], py[0] for i := 1; i <= b3Seg; i++ { x1, y1 := px[i], py[i] b.Line(x0, y0, x1, y1, p) x0, y0 = x1, y1 } } func (b *Bitmap) Bézier3Rgb(x1, y1, x2, y2, x3, y3, x4, y4 int, c Rgb) { b.Bézier3(x1, y1, x2, y2, x3, y3, x4, y4, c.Pixel()) }
Convert this PHP block to Go, preserving its control flow and logic.
<?php $ldap = ldap_connect($hostname, $port); $success = ldap_bind($ldap, $username, $password);
package main import ( "log" "github.com/jtblin/go-ldap-client" ) func main() { client := &ldap.LDAPClient{ Base: "dc=example,dc=com", Host: "ldap.example.com", Port: 389, UseSSL: false, BindDN: "uid=readonlyuser,ou=People,dc=example,dc=com", BindPassword: "readonlypassword", UserFilter: "(uid=%s)", GroupFilter: "(memberUid=%s)", Attributes: []string{"givenName", "sn", "mail", "uid"}, } defer client.Close() err := client.Connect() if err != nil { log.Fatalf("Failed to connect : %+v", err) } }
Generate an equivalent Go version of this PHP code.
<?php $ldap = ldap_connect($hostname, $port); $success = ldap_bind($ldap, $username, $password);
package main import ( "log" "github.com/jtblin/go-ldap-client" ) func main() { client := &ldap.LDAPClient{ Base: "dc=example,dc=com", Host: "ldap.example.com", Port: 389, UseSSL: false, BindDN: "uid=readonlyuser,ou=People,dc=example,dc=com", BindPassword: "readonlypassword", UserFilter: "(uid=%s)", GroupFilter: "(memberUid=%s)", Attributes: []string{"givenName", "sn", "mail", "uid"}, } defer client.Close() err := client.Connect() if err != nil { log.Fatalf("Failed to connect : %+v", err) } }
Port the following code from PHP to Go with equivalent syntax and logic.
<?php $conf = file_get_contents('update-conf-file.txt'); $conf = preg_replace('/^(needspeeling)(|\s*\S*)$/mi', '; $1', $conf); $conf = preg_replace('/^;?\s*(seedsremoved)/mi', '$1', $conf); $conf = preg_replace('/^(numberofbananas)(|\s*\S*)$/mi', '$1 1024', $conf); if (preg_match('/^;?\s*(numberofstrawberries)/mi', $conf, $matches)) { $conf = preg_replace('/^(numberofstrawberries)(|\s*\S*)$/mi', '$1 62000', $conf); } else { $conf .= 'NUMBEROFSTRAWBERRIES 62000' . PHP_EOL; } echo $conf;
package main import ( "bufio" "fmt" "io" "log" "os" "strings" "unicode" ) type line struct { kind lineKind option string value string disabled bool } type lineKind int const ( _ lineKind = iota ignore parseError comment blank value ) func (l line) String() string { switch l.kind { case ignore, parseError, comment, blank: return l.value case value: s := l.option if l.disabled { s = "; " + s } if l.value != "" { s += " " + l.value } return s } panic("unexpected line kind") } func removeDross(s string) string { return strings.Map(func(r rune) rune { if r < 32 || r > 0x7f || unicode.IsControl(r) { return -1 } return r }, s) } func parseLine(s string) line { if s == "" { return line{kind: blank} } if s[0] == '#' { return line{kind: comment, value: s} } s = removeDross(s) fields := strings.Fields(s) if len(fields) == 0 { return line{kind: blank} } semi := false for len(fields[0]) > 0 && fields[0][0] == ';' { semi = true fields[0] = fields[0][1:] } if fields[0] == "" { fields = fields[1:] } switch len(fields) { case 0: return line{kind: ignore} case 1: return line{ kind: value, option: strings.ToUpper(fields[0]), disabled: semi, } case 2: return line{ kind: value, option: strings.ToUpper(fields[0]), value: fields[1], disabled: semi, } } return line{kind: parseError, value: s} } type Config struct { options map[string]int lines []line } func (c *Config) index(option string) int { if i, ok := c.options[option]; ok { return i } return -1 } func (c *Config) addLine(l line) { switch l.kind { case ignore: return case value: if c.index(l.option) >= 0 { return } c.options[l.option] = len(c.lines) c.lines = append(c.lines, l) default: c.lines = append(c.lines, l) } } func ReadConfig(path string) (*Config, error) { f, err := os.Open(path) if err != nil { return nil, err } defer f.Close() r := bufio.NewReader(f) c := &Config{options: make(map[string]int)} for { s, err := r.ReadString('\n') if s != "" { if err == nil { s = s[:len(s)-1] } c.addLine(parseLine(s)) } if err == io.EOF { break } if err != nil { return nil, err } } return c, nil } func (c *Config) Set(option string, val string) { if i := c.index(option); i >= 0 { line := &c.lines[i] line.disabled = false line.value = val return } c.addLine(line{ kind: value, option: option, value: val, }) } func (c *Config) Enable(option string, enabled bool) { if i := c.index(option); i >= 0 { c.lines[i].disabled = !enabled } } func (c *Config) Write(w io.Writer) { for _, line := range c.lines { fmt.Println(line) } } func main() { c, err := ReadConfig("/tmp/cfg") if err != nil { log.Fatalln(err) } c.Enable("NEEDSPEELING", false) c.Set("SEEDSREMOVED", "") c.Set("NUMBEROFBANANAS", "1024") c.Set("NUMBEROFSTRAWBERRIES", "62000") c.Write(os.Stdout) }
Produce a language-to-language conversion: from PHP to Go, same semantics.
<?php $conf = file_get_contents('update-conf-file.txt'); $conf = preg_replace('/^(needspeeling)(|\s*\S*)$/mi', '; $1', $conf); $conf = preg_replace('/^;?\s*(seedsremoved)/mi', '$1', $conf); $conf = preg_replace('/^(numberofbananas)(|\s*\S*)$/mi', '$1 1024', $conf); if (preg_match('/^;?\s*(numberofstrawberries)/mi', $conf, $matches)) { $conf = preg_replace('/^(numberofstrawberries)(|\s*\S*)$/mi', '$1 62000', $conf); } else { $conf .= 'NUMBEROFSTRAWBERRIES 62000' . PHP_EOL; } echo $conf;
package main import ( "bufio" "fmt" "io" "log" "os" "strings" "unicode" ) type line struct { kind lineKind option string value string disabled bool } type lineKind int const ( _ lineKind = iota ignore parseError comment blank value ) func (l line) String() string { switch l.kind { case ignore, parseError, comment, blank: return l.value case value: s := l.option if l.disabled { s = "; " + s } if l.value != "" { s += " " + l.value } return s } panic("unexpected line kind") } func removeDross(s string) string { return strings.Map(func(r rune) rune { if r < 32 || r > 0x7f || unicode.IsControl(r) { return -1 } return r }, s) } func parseLine(s string) line { if s == "" { return line{kind: blank} } if s[0] == '#' { return line{kind: comment, value: s} } s = removeDross(s) fields := strings.Fields(s) if len(fields) == 0 { return line{kind: blank} } semi := false for len(fields[0]) > 0 && fields[0][0] == ';' { semi = true fields[0] = fields[0][1:] } if fields[0] == "" { fields = fields[1:] } switch len(fields) { case 0: return line{kind: ignore} case 1: return line{ kind: value, option: strings.ToUpper(fields[0]), disabled: semi, } case 2: return line{ kind: value, option: strings.ToUpper(fields[0]), value: fields[1], disabled: semi, } } return line{kind: parseError, value: s} } type Config struct { options map[string]int lines []line } func (c *Config) index(option string) int { if i, ok := c.options[option]; ok { return i } return -1 } func (c *Config) addLine(l line) { switch l.kind { case ignore: return case value: if c.index(l.option) >= 0 { return } c.options[l.option] = len(c.lines) c.lines = append(c.lines, l) default: c.lines = append(c.lines, l) } } func ReadConfig(path string) (*Config, error) { f, err := os.Open(path) if err != nil { return nil, err } defer f.Close() r := bufio.NewReader(f) c := &Config{options: make(map[string]int)} for { s, err := r.ReadString('\n') if s != "" { if err == nil { s = s[:len(s)-1] } c.addLine(parseLine(s)) } if err == io.EOF { break } if err != nil { return nil, err } } return c, nil } func (c *Config) Set(option string, val string) { if i := c.index(option); i >= 0 { line := &c.lines[i] line.disabled = false line.value = val return } c.addLine(line{ kind: value, option: option, value: val, }) } func (c *Config) Enable(option string, enabled bool) { if i := c.index(option); i >= 0 { c.lines[i].disabled = !enabled } } func (c *Config) Write(w io.Writer) { for _, line := range c.lines { fmt.Println(line) } } func main() { c, err := ReadConfig("/tmp/cfg") if err != nil { log.Fatalln(err) } c.Enable("NEEDSPEELING", false) c.Set("SEEDSREMOVED", "") c.Set("NUMBEROFBANANAS", "1024") c.Set("NUMBEROFSTRAWBERRIES", "62000") c.Write(os.Stdout) }
Port the provided PHP code into Go while preserving the original functionality.
<?php $zero = function($f) { return function ($x) { return $x; }; }; $succ = function($n) { return function($f) use (&$n) { return function($x) use (&$n, &$f) { return $f( ($n($f))($x) ); }; }; }; $add = function($n, $m) { return function($f) use (&$n, &$m) { return function($x) use (&$f, &$n, &$m) { return ($m($f))(($n($f))($x)); }; }; }; $mult = function($n, $m) { return function($f) use (&$n, &$m) { return function($x) use (&$f, &$n, &$m) { return ($m($n($f)))($x); }; }; }; $power = function($b,$e) { return $e($b); }; $to_int = function($f) { $count_up = function($i) { return $i+1; }; return ($f($count_up))(0); }; $from_int = function($x) { $countdown = function($i) use (&$countdown) { global $zero, $succ; if ( $i == 0 ) { return $zero; } else { return $succ($countdown($i-1)); }; }; return $countdown($x); }; $three = $succ($succ($succ($zero))); $four = $from_int(4); foreach (array($add($three,$four), $mult($three,$four), $power($three,$four), $power($four,$three)) as $ch) { print($to_int($ch)); print("\n"); } ?>
package main import "fmt" type any = interface{} type fn func(any) any type church func(fn) fn func zero(f fn) fn { return func(x any) any { return x } } func (c church) succ() church { return func(f fn) fn { return func(x any) any { return f(c(f)(x)) } } } func (c church) add(d church) church { return func(f fn) fn { return func(x any) any { return c(f)(d(f)(x)) } } } func (c church) mul(d church) church { return func(f fn) fn { return func(x any) any { return c(d(f))(x) } } } func (c church) pow(d church) church { di := d.toInt() prod := c for i := 1; i < di; i++ { prod = prod.mul(c) } return prod } func (c church) toInt() int { return c(incr)(0).(int) } func intToChurch(i int) church { if i == 0 { return zero } else { return intToChurch(i - 1).succ() } } func incr(i any) any { return i.(int) + 1 } func main() { z := church(zero) three := z.succ().succ().succ() four := three.succ() fmt.Println("three ->", three.toInt()) fmt.Println("four ->", four.toInt()) fmt.Println("three + four ->", three.add(four).toInt()) fmt.Println("three * four ->", three.mul(four).toInt()) fmt.Println("three ^ four ->", three.pow(four).toInt()) fmt.Println("four ^ three ->", four.pow(three).toInt()) fmt.Println("5 -> five ->", intToChurch(5).toInt()) }
Produce a functionally identical Go code for the snippet given in PHP.
<?php $zero = function($f) { return function ($x) { return $x; }; }; $succ = function($n) { return function($f) use (&$n) { return function($x) use (&$n, &$f) { return $f( ($n($f))($x) ); }; }; }; $add = function($n, $m) { return function($f) use (&$n, &$m) { return function($x) use (&$f, &$n, &$m) { return ($m($f))(($n($f))($x)); }; }; }; $mult = function($n, $m) { return function($f) use (&$n, &$m) { return function($x) use (&$f, &$n, &$m) { return ($m($n($f)))($x); }; }; }; $power = function($b,$e) { return $e($b); }; $to_int = function($f) { $count_up = function($i) { return $i+1; }; return ($f($count_up))(0); }; $from_int = function($x) { $countdown = function($i) use (&$countdown) { global $zero, $succ; if ( $i == 0 ) { return $zero; } else { return $succ($countdown($i-1)); }; }; return $countdown($x); }; $three = $succ($succ($succ($zero))); $four = $from_int(4); foreach (array($add($three,$four), $mult($three,$four), $power($three,$four), $power($four,$three)) as $ch) { print($to_int($ch)); print("\n"); } ?>
package main import "fmt" type any = interface{} type fn func(any) any type church func(fn) fn func zero(f fn) fn { return func(x any) any { return x } } func (c church) succ() church { return func(f fn) fn { return func(x any) any { return f(c(f)(x)) } } } func (c church) add(d church) church { return func(f fn) fn { return func(x any) any { return c(f)(d(f)(x)) } } } func (c church) mul(d church) church { return func(f fn) fn { return func(x any) any { return c(d(f))(x) } } } func (c church) pow(d church) church { di := d.toInt() prod := c for i := 1; i < di; i++ { prod = prod.mul(c) } return prod } func (c church) toInt() int { return c(incr)(0).(int) } func intToChurch(i int) church { if i == 0 { return zero } else { return intToChurch(i - 1).succ() } } func incr(i any) any { return i.(int) + 1 } func main() { z := church(zero) three := z.succ().succ().succ() four := three.succ() fmt.Println("three ->", three.toInt()) fmt.Println("four ->", four.toInt()) fmt.Println("three + four ->", three.add(four).toInt()) fmt.Println("three * four ->", three.mul(four).toInt()) fmt.Println("three ^ four ->", three.pow(four).toInt()) fmt.Println("four ^ three ->", four.pow(three).toInt()) fmt.Println("5 -> five ->", intToChurch(5).toInt()) }
Translate the given PHP code snippet into Go without altering its behavior.
<?php $zero = function($f) { return function ($x) { return $x; }; }; $succ = function($n) { return function($f) use (&$n) { return function($x) use (&$n, &$f) { return $f( ($n($f))($x) ); }; }; }; $add = function($n, $m) { return function($f) use (&$n, &$m) { return function($x) use (&$f, &$n, &$m) { return ($m($f))(($n($f))($x)); }; }; }; $mult = function($n, $m) { return function($f) use (&$n, &$m) { return function($x) use (&$f, &$n, &$m) { return ($m($n($f)))($x); }; }; }; $power = function($b,$e) { return $e($b); }; $to_int = function($f) { $count_up = function($i) { return $i+1; }; return ($f($count_up))(0); }; $from_int = function($x) { $countdown = function($i) use (&$countdown) { global $zero, $succ; if ( $i == 0 ) { return $zero; } else { return $succ($countdown($i-1)); }; }; return $countdown($x); }; $three = $succ($succ($succ($zero))); $four = $from_int(4); foreach (array($add($three,$four), $mult($three,$four), $power($three,$four), $power($four,$three)) as $ch) { print($to_int($ch)); print("\n"); } ?>
package main import "fmt" type any = interface{} type fn func(any) any type church func(fn) fn func zero(f fn) fn { return func(x any) any { return x } } func (c church) succ() church { return func(f fn) fn { return func(x any) any { return f(c(f)(x)) } } } func (c church) add(d church) church { return func(f fn) fn { return func(x any) any { return c(f)(d(f)(x)) } } } func (c church) mul(d church) church { return func(f fn) fn { return func(x any) any { return c(d(f))(x) } } } func (c church) pow(d church) church { di := d.toInt() prod := c for i := 1; i < di; i++ { prod = prod.mul(c) } return prod } func (c church) toInt() int { return c(incr)(0).(int) } func intToChurch(i int) church { if i == 0 { return zero } else { return intToChurch(i - 1).succ() } } func incr(i any) any { return i.(int) + 1 } func main() { z := church(zero) three := z.succ().succ().succ() four := three.succ() fmt.Println("three ->", three.toInt()) fmt.Println("four ->", four.toInt()) fmt.Println("three + four ->", three.add(four).toInt()) fmt.Println("three * four ->", three.mul(four).toInt()) fmt.Println("three ^ four ->", three.pow(four).toInt()) fmt.Println("four ^ three ->", four.pow(three).toInt()) fmt.Println("5 -> five ->", intToChurch(5).toInt()) }
Generate an equivalent Go version of this PHP code.
<?php $zero = function($f) { return function ($x) { return $x; }; }; $succ = function($n) { return function($f) use (&$n) { return function($x) use (&$n, &$f) { return $f( ($n($f))($x) ); }; }; }; $add = function($n, $m) { return function($f) use (&$n, &$m) { return function($x) use (&$f, &$n, &$m) { return ($m($f))(($n($f))($x)); }; }; }; $mult = function($n, $m) { return function($f) use (&$n, &$m) { return function($x) use (&$f, &$n, &$m) { return ($m($n($f)))($x); }; }; }; $power = function($b,$e) { return $e($b); }; $to_int = function($f) { $count_up = function($i) { return $i+1; }; return ($f($count_up))(0); }; $from_int = function($x) { $countdown = function($i) use (&$countdown) { global $zero, $succ; if ( $i == 0 ) { return $zero; } else { return $succ($countdown($i-1)); }; }; return $countdown($x); }; $three = $succ($succ($succ($zero))); $four = $from_int(4); foreach (array($add($three,$four), $mult($three,$four), $power($three,$four), $power($four,$three)) as $ch) { print($to_int($ch)); print("\n"); } ?>
package main import "fmt" type any = interface{} type fn func(any) any type church func(fn) fn func zero(f fn) fn { return func(x any) any { return x } } func (c church) succ() church { return func(f fn) fn { return func(x any) any { return f(c(f)(x)) } } } func (c church) add(d church) church { return func(f fn) fn { return func(x any) any { return c(f)(d(f)(x)) } } } func (c church) mul(d church) church { return func(f fn) fn { return func(x any) any { return c(d(f))(x) } } } func (c church) pow(d church) church { di := d.toInt() prod := c for i := 1; i < di; i++ { prod = prod.mul(c) } return prod } func (c church) toInt() int { return c(incr)(0).(int) } func intToChurch(i int) church { if i == 0 { return zero } else { return intToChurch(i - 1).succ() } } func incr(i any) any { return i.(int) + 1 } func main() { z := church(zero) three := z.succ().succ().succ() four := three.succ() fmt.Println("three ->", three.toInt()) fmt.Println("four ->", four.toInt()) fmt.Println("three + four ->", three.add(four).toInt()) fmt.Println("three * four ->", three.mul(four).toInt()) fmt.Println("three ^ four ->", three.pow(four).toInt()) fmt.Println("four ^ three ->", four.pow(three).toInt()) fmt.Println("5 -> five ->", intToChurch(5).toInt()) }
Write the same code in Go as shown below in PHP.
<?php class SimpleClass { private $answer = "hello\"world\nforever :)"; } $class = new SimpleClass; ob_start(); var_export($class); $class_content = ob_get_clean(); $class_content = preg_replace('"^SimpleClass::__set_state\("', 'return ', $class_content); $class_content = preg_replace('"\)$"', ';', $class_content); $new_class = eval($class_content); echo $new_class['answer'];
package main import ( "bufio" "errors" "fmt" "os" "reflect" "unsafe" ) type foobar struct { Exported int unexported int } func main() { obj := foobar{12, 42} fmt.Println("obj:", obj) examineAndModify(&obj) fmt.Println("obj:", obj) anotherExample() } func examineAndModify(any interface{}) { v := reflect.ValueOf(any) v = v.Elem() fmt.Println(" v:", v, "=", v.Interface()) t := v.Type() fmt.Printf(" %3s %-10s %-4s %s\n", "Idx", "Name", "Type", "CanSet") for i := 0; i < v.NumField(); i++ { f := v.Field(i) fmt.Printf(" %2d: %-10s %-4s %t\n", i, t.Field(i).Name, f.Type(), f.CanSet()) } v.Field(0).SetInt(16) vp := v.Field(1).Addr() up := unsafe.Pointer(vp.Pointer()) p := (*int)(up) fmt.Printf(" vp has type %-14T = %v\n", vp, vp) fmt.Printf(" up has type %-14T = %#0x\n", up, up) fmt.Printf(" p has type %-14T = %v pointing at %v\n", p, p, *p) *p = 43 *(*int)(unsafe.Pointer(v.Field(1).Addr().Pointer()))++ } func anotherExample() { r := bufio.NewReader(os.Stdin) errp := (*error)(unsafe.Pointer( reflect.ValueOf(r).Elem().FieldByName("err").Addr().Pointer())) *errp = errors.New("unsafely injected error value into bufio inner workings") _, err := r.ReadByte() fmt.Println("bufio.ReadByte returned error:", err) }
Translate this program into Go but keep the logic exactly as in PHP.
<?php class SimpleClass { private $answer = "hello\"world\nforever :)"; } $class = new SimpleClass; ob_start(); var_export($class); $class_content = ob_get_clean(); $class_content = preg_replace('"^SimpleClass::__set_state\("', 'return ', $class_content); $class_content = preg_replace('"\)$"', ';', $class_content); $new_class = eval($class_content); echo $new_class['answer'];
package main import ( "bufio" "errors" "fmt" "os" "reflect" "unsafe" ) type foobar struct { Exported int unexported int } func main() { obj := foobar{12, 42} fmt.Println("obj:", obj) examineAndModify(&obj) fmt.Println("obj:", obj) anotherExample() } func examineAndModify(any interface{}) { v := reflect.ValueOf(any) v = v.Elem() fmt.Println(" v:", v, "=", v.Interface()) t := v.Type() fmt.Printf(" %3s %-10s %-4s %s\n", "Idx", "Name", "Type", "CanSet") for i := 0; i < v.NumField(); i++ { f := v.Field(i) fmt.Printf(" %2d: %-10s %-4s %t\n", i, t.Field(i).Name, f.Type(), f.CanSet()) } v.Field(0).SetInt(16) vp := v.Field(1).Addr() up := unsafe.Pointer(vp.Pointer()) p := (*int)(up) fmt.Printf(" vp has type %-14T = %v\n", vp, vp) fmt.Printf(" up has type %-14T = %#0x\n", up, up) fmt.Printf(" p has type %-14T = %v pointing at %v\n", p, p, *p) *p = 43 *(*int)(unsafe.Pointer(v.Field(1).Addr().Pointer()))++ } func anotherExample() { r := bufio.NewReader(os.Stdin) errp := (*error)(unsafe.Pointer( reflect.ValueOf(r).Elem().FieldByName("err").Addr().Pointer())) *errp = errors.New("unsafely injected error value into bufio inner workings") _, err := r.ReadByte() fmt.Println("bufio.ReadByte returned error:", err) }
Maintain the same structure and functionality when rewriting this code in Go.
<?php class SimpleClass { private $answer = "hello\"world\nforever :)"; } $class = new SimpleClass; ob_start(); var_export($class); $class_content = ob_get_clean(); $class_content = preg_replace('"^SimpleClass::__set_state\("', 'return ', $class_content); $class_content = preg_replace('"\)$"', ';', $class_content); $new_class = eval($class_content); echo $new_class['answer'];
package main import ( "bufio" "errors" "fmt" "os" "reflect" "unsafe" ) type foobar struct { Exported int unexported int } func main() { obj := foobar{12, 42} fmt.Println("obj:", obj) examineAndModify(&obj) fmt.Println("obj:", obj) anotherExample() } func examineAndModify(any interface{}) { v := reflect.ValueOf(any) v = v.Elem() fmt.Println(" v:", v, "=", v.Interface()) t := v.Type() fmt.Printf(" %3s %-10s %-4s %s\n", "Idx", "Name", "Type", "CanSet") for i := 0; i < v.NumField(); i++ { f := v.Field(i) fmt.Printf(" %2d: %-10s %-4s %t\n", i, t.Field(i).Name, f.Type(), f.CanSet()) } v.Field(0).SetInt(16) vp := v.Field(1).Addr() up := unsafe.Pointer(vp.Pointer()) p := (*int)(up) fmt.Printf(" vp has type %-14T = %v\n", vp, vp) fmt.Printf(" up has type %-14T = %#0x\n", up, up) fmt.Printf(" p has type %-14T = %v pointing at %v\n", p, p, *p) *p = 43 *(*int)(unsafe.Pointer(v.Field(1).Addr().Pointer()))++ } func anotherExample() { r := bufio.NewReader(os.Stdin) errp := (*error)(unsafe.Pointer( reflect.ValueOf(r).Elem().FieldByName("err").Addr().Pointer())) *errp = errors.New("unsafely injected error value into bufio inner workings") _, err := r.ReadByte() fmt.Println("bufio.ReadByte returned error:", err) }
Can you help me rewrite this code in Go instead of PHP, keeping it the same logically?
<?php class SimpleClass { private $answer = "hello\"world\nforever :)"; } $class = new SimpleClass; ob_start(); var_export($class); $class_content = ob_get_clean(); $class_content = preg_replace('"^SimpleClass::__set_state\("', 'return ', $class_content); $class_content = preg_replace('"\)$"', ';', $class_content); $new_class = eval($class_content); echo $new_class['answer'];
package main import ( "bufio" "errors" "fmt" "os" "reflect" "unsafe" ) type foobar struct { Exported int unexported int } func main() { obj := foobar{12, 42} fmt.Println("obj:", obj) examineAndModify(&obj) fmt.Println("obj:", obj) anotherExample() } func examineAndModify(any interface{}) { v := reflect.ValueOf(any) v = v.Elem() fmt.Println(" v:", v, "=", v.Interface()) t := v.Type() fmt.Printf(" %3s %-10s %-4s %s\n", "Idx", "Name", "Type", "CanSet") for i := 0; i < v.NumField(); i++ { f := v.Field(i) fmt.Printf(" %2d: %-10s %-4s %t\n", i, t.Field(i).Name, f.Type(), f.CanSet()) } v.Field(0).SetInt(16) vp := v.Field(1).Addr() up := unsafe.Pointer(vp.Pointer()) p := (*int)(up) fmt.Printf(" vp has type %-14T = %v\n", vp, vp) fmt.Printf(" up has type %-14T = %#0x\n", up, up) fmt.Printf(" p has type %-14T = %v pointing at %v\n", p, p, *p) *p = 43 *(*int)(unsafe.Pointer(v.Field(1).Addr().Pointer()))++ } func anotherExample() { r := bufio.NewReader(os.Stdin) errp := (*error)(unsafe.Pointer( reflect.ValueOf(r).Elem().FieldByName("err").Addr().Pointer())) *errp = errors.New("unsafely injected error value into bufio inner workings") _, err := r.ReadByte() fmt.Println("bufio.ReadByte returned error:", err) }
Port the following code from PHP to Go with equivalent syntax and logic.
$myObj = new Object(); $serializedObj = serialize($myObj);
package main import ( "encoding/gob" "fmt" "os" ) type printable interface { print() } func main() { animals := []printable{ &Animal{Alive: true}, &Cat{}, &Lab{ Dog: Dog{Animal: Animal{Alive: true}}, Color: "yellow", }, &Collie{Dog: Dog{ Animal: Animal{Alive: true}, ObedienceTrained: true, }}, } fmt.Println("created:") for _, a := range animals { a.print() } f, err := os.Create("objects.dat") if err != nil { fmt.Println(err) return } for _, a := range animals { gob.Register(a) } err = gob.NewEncoder(f).Encode(animals) if err != nil { fmt.Println(err) return } f.Close() f, err = os.Open("objects.dat") if err != nil { fmt.Println(err) return } var clones []printable gob.NewDecoder(f).Decode(&clones) if err != nil { fmt.Println(err) return } fmt.Println("\nloaded from objects.dat:") for _, c := range clones { c.print() } } type Animal struct { Alive bool } func (a *Animal) print() { if a.Alive { fmt.Println(" live animal, unspecified type") } else { fmt.Println(" dead animal, unspecified type") } } type Dog struct { Animal ObedienceTrained bool } func (d *Dog) print() { switch { case !d.Alive: fmt.Println(" dead dog") case d.ObedienceTrained: fmt.Println(" trained dog") default: fmt.Println(" dog, not trained") } } type Cat struct { Animal LitterBoxTrained bool } func (c *Cat) print() { switch { case !c.Alive: fmt.Println(" dead cat") case c.LitterBoxTrained: fmt.Println(" litter box trained cat") default: fmt.Println(" cat, not litter box trained") } } type Lab struct { Dog Color string } func (l *Lab) print() { var r string if l.Color == "" { r = "lab, color unspecified" } else { r = l.Color + " lab" } switch { case !l.Alive: fmt.Println(" dead", r) case l.ObedienceTrained: fmt.Println(" trained", r) default: fmt.Printf(" %s, not trained\n", r) } } type Collie struct { Dog CatchesFrisbee bool } func (c *Collie) print() { switch { case !c.Alive: fmt.Println(" dead collie") case c.ObedienceTrained && c.CatchesFrisbee: fmt.Println(" trained collie, catches frisbee") case c.ObedienceTrained && !c.CatchesFrisbee: fmt.Println(" trained collie, but doesn't catch frisbee") case !c.ObedienceTrained && c.CatchesFrisbee: fmt.Println(" collie, not trained, but catches frisbee") case !c.ObedienceTrained && !c.CatchesFrisbee: fmt.Println(" collie, not trained, doesn't catch frisbee") } }
Convert the following code from PHP to Go, ensuring the logic remains intact.
$myObj = new Object(); $serializedObj = serialize($myObj);
package main import ( "encoding/gob" "fmt" "os" ) type printable interface { print() } func main() { animals := []printable{ &Animal{Alive: true}, &Cat{}, &Lab{ Dog: Dog{Animal: Animal{Alive: true}}, Color: "yellow", }, &Collie{Dog: Dog{ Animal: Animal{Alive: true}, ObedienceTrained: true, }}, } fmt.Println("created:") for _, a := range animals { a.print() } f, err := os.Create("objects.dat") if err != nil { fmt.Println(err) return } for _, a := range animals { gob.Register(a) } err = gob.NewEncoder(f).Encode(animals) if err != nil { fmt.Println(err) return } f.Close() f, err = os.Open("objects.dat") if err != nil { fmt.Println(err) return } var clones []printable gob.NewDecoder(f).Decode(&clones) if err != nil { fmt.Println(err) return } fmt.Println("\nloaded from objects.dat:") for _, c := range clones { c.print() } } type Animal struct { Alive bool } func (a *Animal) print() { if a.Alive { fmt.Println(" live animal, unspecified type") } else { fmt.Println(" dead animal, unspecified type") } } type Dog struct { Animal ObedienceTrained bool } func (d *Dog) print() { switch { case !d.Alive: fmt.Println(" dead dog") case d.ObedienceTrained: fmt.Println(" trained dog") default: fmt.Println(" dog, not trained") } } type Cat struct { Animal LitterBoxTrained bool } func (c *Cat) print() { switch { case !c.Alive: fmt.Println(" dead cat") case c.LitterBoxTrained: fmt.Println(" litter box trained cat") default: fmt.Println(" cat, not litter box trained") } } type Lab struct { Dog Color string } func (l *Lab) print() { var r string if l.Color == "" { r = "lab, color unspecified" } else { r = l.Color + " lab" } switch { case !l.Alive: fmt.Println(" dead", r) case l.ObedienceTrained: fmt.Println(" trained", r) default: fmt.Printf(" %s, not trained\n", r) } } type Collie struct { Dog CatchesFrisbee bool } func (c *Collie) print() { switch { case !c.Alive: fmt.Println(" dead collie") case c.ObedienceTrained && c.CatchesFrisbee: fmt.Println(" trained collie, catches frisbee") case c.ObedienceTrained && !c.CatchesFrisbee: fmt.Println(" trained collie, but doesn't catch frisbee") case !c.ObedienceTrained && c.CatchesFrisbee: fmt.Println(" collie, not trained, but catches frisbee") case !c.ObedienceTrained && !c.CatchesFrisbee: fmt.Println(" collie, not trained, doesn't catch frisbee") } }
Translate this program into Go but keep the logic exactly as in PHP.
function isLongYear($year) { return (53 == strftime('%V', gmmktime(0,0,0,12,28,$year))); } for ($y=1995; $y<=2045; ++$y) { if (isLongYear($y)) { printf("%s\n", $y); } }
package main import ( "fmt" "time" ) func main() { centuries := []string{"20th", "21st", "22nd"} starts := []int{1900, 2000, 2100} for i := 0; i < len(centuries); i++ { var longYears []int fmt.Printf("\nLong years in the %s century:\n", centuries[i]) for j := starts[i]; j < starts[i] + 100; j++ { t := time.Date(j, time.December, 28, 0, 0, 0, 0, time.UTC) if _, week := t.ISOWeek(); week == 53 { longYears = append(longYears, j) } } fmt.Println(longYears) } }
Can you help me rewrite this code in Go instead of PHP, keeping it the same logically?
function isLongYear($year) { return (53 == strftime('%V', gmmktime(0,0,0,12,28,$year))); } for ($y=1995; $y<=2045; ++$y) { if (isLongYear($y)) { printf("%s\n", $y); } }
package main import ( "fmt" "time" ) func main() { centuries := []string{"20th", "21st", "22nd"} starts := []int{1900, 2000, 2100} for i := 0; i < len(centuries); i++ { var longYears []int fmt.Printf("\nLong years in the %s century:\n", centuries[i]) for j := starts[i]; j < starts[i] + 100; j++ { t := time.Date(j, time.December, 28, 0, 0, 0, 0, time.UTC) if _, week := t.ISOWeek(); week == 53 { longYears = append(longYears, j) } } fmt.Println(longYears) } }
Generate an equivalent Go version of this PHP code.
<? $base = array("name" => "Rocket Skates", "price" => 12.75, "color" => "yellow"); $update = array("price" => 15.25, "color" => "red", "year" => 1974); $result = $update + $base; // Notice that the order is reversed print_r($result); ?>
package main import "fmt" type assoc map[string]interface{} func merge(base, update assoc) assoc { result := make(assoc) for k, v := range base { result[k] = v } for k, v := range update { result[k] = v } return result } func main() { base := assoc{"name": "Rocket Skates", "price": 12.75, "color": "yellow"} update := assoc{"price": 15.25, "color": "red", "year": 1974} result := merge(base, update) fmt.Println(result) }
Port the provided PHP code into Go while preserving the original functionality.
<? $base = array("name" => "Rocket Skates", "price" => 12.75, "color" => "yellow"); $update = array("price" => 15.25, "color" => "red", "year" => 1974); $result = $update + $base; // Notice that the order is reversed print_r($result); ?>
package main import "fmt" type assoc map[string]interface{} func merge(base, update assoc) assoc { result := make(assoc) for k, v := range base { result[k] = v } for k, v := range update { result[k] = v } return result } func main() { base := assoc{"name": "Rocket Skates", "price": 12.75, "color": "yellow"} update := assoc{"price": 15.25, "color": "red", "year": 1974} result := merge(base, update) fmt.Println(result) }
Generate an equivalent Go version of this PHP code.
<? $base = array("name" => "Rocket Skates", "price" => 12.75, "color" => "yellow"); $update = array("price" => 15.25, "color" => "red", "year" => 1974); $result = $update + $base; // Notice that the order is reversed print_r($result); ?>
package main import "fmt" type assoc map[string]interface{} func merge(base, update assoc) assoc { result := make(assoc) for k, v := range base { result[k] = v } for k, v := range update { result[k] = v } return result } func main() { base := assoc{"name": "Rocket Skates", "price": 12.75, "color": "yellow"} update := assoc{"price": 15.25, "color": "red", "year": 1974} result := merge(base, update) fmt.Println(result) }
Rewrite the snippet below in Go so it works the same as the original PHP code.
<? $base = array("name" => "Rocket Skates", "price" => 12.75, "color" => "yellow"); $update = array("price" => 15.25, "color" => "red", "year" => 1974); $result = $update + $base; // Notice that the order is reversed print_r($result); ?>
package main import "fmt" type assoc map[string]interface{} func merge(base, update assoc) assoc { result := make(assoc) for k, v := range base { result[k] = v } for k, v := range update { result[k] = v } return result } func main() { base := assoc{"name": "Rocket Skates", "price": 12.75, "color": "yellow"} update := assoc{"price": 15.25, "color": "red", "year": 1974} result := merge(base, update) fmt.Println(result) }
Port the provided PHP code into Go while preserving the original functionality.
<?php function markovChainTextGenerator($text, $keySize, $maxWords) { $token = array(); $position = 0; $maxPosition = strlen($text); while ($position < $maxPosition) { if (preg_match('/^(\S+)/', substr($text, $position, 25), $matches)) { $token[] = $matches[1]; $position += strlen($matches[1]); } elseif (preg_match('/^(\s+)/', substr($text, $position, 25), $matches)) { $position += strlen($matches[1]); } else { die( 'Unknown token found at position ' . $position . ' : ' . substr($text, $position, 25) . '...' . PHP_EOL ); } } $dictionary = array(); for ($i = 0 ; $i < count($token) - $keySize ; $i++) { $prefix = ''; $separator = ''; for ($c = 0 ; $c < $keySize ; $c++) { $prefix .= $separator . $token[$i + $c]; $separator = '.'; } $dictionary[$prefix][] = $token[$i + $keySize]; } $rand = rand(0, count($token) - $keySize); $startToken = array(); for ($c = 0 ; $c < $keySize ; $c++) { array_push($startToken, $token[$rand + $c]); } $text = implode(' ', $startToken); $words = $keySize; do { $tokenKey = implode('.', $startToken); $rand = rand(0, count($dictionary[$tokenKey]) - 1); $newToken = $dictionary[$tokenKey][$rand]; $text .= ' ' . $newToken; $words++; array_shift($startToken); array_push($startToken, $newToken); } while($words < $maxWords); return $text; } srand(5678); $text = markovChainTextGenerator( file_get_contents(__DIR__ . '/inc/alice_oz.txt'), 3, 308 ); echo wordwrap($text, 100, PHP_EOL) . PHP_EOL;
package main import ( "bufio" "flag" "fmt" "io" "log" "math/rand" "os" "strings" "time" "unicode" "unicode/utf8" ) func main() { log.SetFlags(0) log.SetPrefix("markov: ") input := flag.String("in", "alice_oz.txt", "input file") n := flag.Int("n", 2, "number of words to use as prefix") runs := flag.Int("runs", 1, "number of runs to generate") wordsPerRun := flag.Int("words", 300, "number of words per run") startOnCapital := flag.Bool("capital", false, "start output with a capitalized prefix") stopAtSentence := flag.Bool("sentence", false, "end output at a sentence ending punctuation mark (after n words)") flag.Parse() rand.Seed(time.Now().UnixNano()) m, err := NewMarkovFromFile(*input, *n) if err != nil { log.Fatal(err) } for i := 0; i < *runs; i++ { err = m.Output(os.Stdout, *wordsPerRun, *startOnCapital, *stopAtSentence) if err != nil { log.Fatal(err) } fmt.Println() } } type Markov struct { n int capitalized int suffix map[string][]string } func NewMarkovFromFile(filename string, n int) (*Markov, error) { f, err := os.Open(filename) if err != nil { return nil, err } defer f.Close() return NewMarkov(f, n) } func NewMarkov(r io.Reader, n int) (*Markov, error) { m := &Markov{ n: n, suffix: make(map[string][]string), } sc := bufio.NewScanner(r) sc.Split(bufio.ScanWords) window := make([]string, 0, n) for sc.Scan() { word := sc.Text() if len(window) > 0 { prefix := strings.Join(window, " ") m.suffix[prefix] = append(m.suffix[prefix], word) if isCapitalized(prefix) { m.capitalized++ } } window = appendMax(n, window, word) } if err := sc.Err(); err != nil { return nil, err } return m, nil } func (m *Markov) Output(w io.Writer, n int, startCapital, stopSentence bool) error { bw := bufio.NewWriter(w) var i int if startCapital { i = rand.Intn(m.capitalized) } else { i = rand.Intn(len(m.suffix)) } var prefix string for prefix = range m.suffix { if startCapital && !isCapitalized(prefix) { continue } if i == 0 { break } i-- } bw.WriteString(prefix) prefixWords := strings.Fields(prefix) n -= len(prefixWords) for { suffixChoices := m.suffix[prefix] if len(suffixChoices) == 0 { break } i = rand.Intn(len(suffixChoices)) suffix := suffixChoices[i] bw.WriteByte(' ') if _, err := bw.WriteString(suffix); err != nil { break } n-- if n < 0 && (!stopSentence || isSentenceEnd(suffix)) { break } prefixWords = appendMax(m.n, prefixWords, suffix) prefix = strings.Join(prefixWords, " ") } return bw.Flush() } func isCapitalized(s string) bool { r, _ := utf8.DecodeRuneInString(s) return unicode.IsUpper(r) } func isSentenceEnd(s string) bool { r, _ := utf8.DecodeLastRuneInString(s) return r == '.' || r == '?' || r == '!' } func appendMax(max int, slice []string, value string) []string { if len(slice)+1 > max { n := copy(slice, slice[1:]) slice = slice[:n] } return append(slice, value) }
Rewrite this program in Go while keeping its functionality equivalent to the PHP version.
<?php function markovChainTextGenerator($text, $keySize, $maxWords) { $token = array(); $position = 0; $maxPosition = strlen($text); while ($position < $maxPosition) { if (preg_match('/^(\S+)/', substr($text, $position, 25), $matches)) { $token[] = $matches[1]; $position += strlen($matches[1]); } elseif (preg_match('/^(\s+)/', substr($text, $position, 25), $matches)) { $position += strlen($matches[1]); } else { die( 'Unknown token found at position ' . $position . ' : ' . substr($text, $position, 25) . '...' . PHP_EOL ); } } $dictionary = array(); for ($i = 0 ; $i < count($token) - $keySize ; $i++) { $prefix = ''; $separator = ''; for ($c = 0 ; $c < $keySize ; $c++) { $prefix .= $separator . $token[$i + $c]; $separator = '.'; } $dictionary[$prefix][] = $token[$i + $keySize]; } $rand = rand(0, count($token) - $keySize); $startToken = array(); for ($c = 0 ; $c < $keySize ; $c++) { array_push($startToken, $token[$rand + $c]); } $text = implode(' ', $startToken); $words = $keySize; do { $tokenKey = implode('.', $startToken); $rand = rand(0, count($dictionary[$tokenKey]) - 1); $newToken = $dictionary[$tokenKey][$rand]; $text .= ' ' . $newToken; $words++; array_shift($startToken); array_push($startToken, $newToken); } while($words < $maxWords); return $text; } srand(5678); $text = markovChainTextGenerator( file_get_contents(__DIR__ . '/inc/alice_oz.txt'), 3, 308 ); echo wordwrap($text, 100, PHP_EOL) . PHP_EOL;
package main import ( "bufio" "flag" "fmt" "io" "log" "math/rand" "os" "strings" "time" "unicode" "unicode/utf8" ) func main() { log.SetFlags(0) log.SetPrefix("markov: ") input := flag.String("in", "alice_oz.txt", "input file") n := flag.Int("n", 2, "number of words to use as prefix") runs := flag.Int("runs", 1, "number of runs to generate") wordsPerRun := flag.Int("words", 300, "number of words per run") startOnCapital := flag.Bool("capital", false, "start output with a capitalized prefix") stopAtSentence := flag.Bool("sentence", false, "end output at a sentence ending punctuation mark (after n words)") flag.Parse() rand.Seed(time.Now().UnixNano()) m, err := NewMarkovFromFile(*input, *n) if err != nil { log.Fatal(err) } for i := 0; i < *runs; i++ { err = m.Output(os.Stdout, *wordsPerRun, *startOnCapital, *stopAtSentence) if err != nil { log.Fatal(err) } fmt.Println() } } type Markov struct { n int capitalized int suffix map[string][]string } func NewMarkovFromFile(filename string, n int) (*Markov, error) { f, err := os.Open(filename) if err != nil { return nil, err } defer f.Close() return NewMarkov(f, n) } func NewMarkov(r io.Reader, n int) (*Markov, error) { m := &Markov{ n: n, suffix: make(map[string][]string), } sc := bufio.NewScanner(r) sc.Split(bufio.ScanWords) window := make([]string, 0, n) for sc.Scan() { word := sc.Text() if len(window) > 0 { prefix := strings.Join(window, " ") m.suffix[prefix] = append(m.suffix[prefix], word) if isCapitalized(prefix) { m.capitalized++ } } window = appendMax(n, window, word) } if err := sc.Err(); err != nil { return nil, err } return m, nil } func (m *Markov) Output(w io.Writer, n int, startCapital, stopSentence bool) error { bw := bufio.NewWriter(w) var i int if startCapital { i = rand.Intn(m.capitalized) } else { i = rand.Intn(len(m.suffix)) } var prefix string for prefix = range m.suffix { if startCapital && !isCapitalized(prefix) { continue } if i == 0 { break } i-- } bw.WriteString(prefix) prefixWords := strings.Fields(prefix) n -= len(prefixWords) for { suffixChoices := m.suffix[prefix] if len(suffixChoices) == 0 { break } i = rand.Intn(len(suffixChoices)) suffix := suffixChoices[i] bw.WriteByte(' ') if _, err := bw.WriteString(suffix); err != nil { break } n-- if n < 0 && (!stopSentence || isSentenceEnd(suffix)) { break } prefixWords = appendMax(m.n, prefixWords, suffix) prefix = strings.Join(prefixWords, " ") } return bw.Flush() } func isCapitalized(s string) bool { r, _ := utf8.DecodeRuneInString(s) return unicode.IsUpper(r) } func isSentenceEnd(s string) bool { r, _ := utf8.DecodeLastRuneInString(s) return r == '.' || r == '?' || r == '!' } func appendMax(max int, slice []string, value string) []string { if len(slice)+1 > max { n := copy(slice, slice[1:]) slice = slice[:n] } return append(slice, value) }
Generate a Go translation of this PHP snippet without changing its computational steps.
<?php function dijkstra($graph_array, $source, $target) { $vertices = array(); $neighbours = array(); foreach ($graph_array as $edge) { array_push($vertices, $edge[0], $edge[1]); $neighbours[$edge[0]][] = array("end" => $edge[1], "cost" => $edge[2]); $neighbours[$edge[1]][] = array("end" => $edge[0], "cost" => $edge[2]); } $vertices = array_unique($vertices); foreach ($vertices as $vertex) { $dist[$vertex] = INF; $previous[$vertex] = NULL; } $dist[$source] = 0; $Q = $vertices; while (count($Q) > 0) { $min = INF; foreach ($Q as $vertex){ if ($dist[$vertex] < $min) { $min = $dist[$vertex]; $u = $vertex; } } $Q = array_diff($Q, array($u)); if ($dist[$u] == INF or $u == $target) { break; } if (isset($neighbours[$u])) { foreach ($neighbours[$u] as $arr) { $alt = $dist[$u] + $arr["cost"]; if ($alt < $dist[$arr["end"]]) { $dist[$arr["end"]] = $alt; $previous[$arr["end"]] = $u; } } } } $path = array(); $u = $target; while (isset($previous[$u])) { array_unshift($path, $u); $u = $previous[$u]; } array_unshift($path, $u); return $path; } $graph_array = array( array("a", "b", 7), array("a", "c", 9), array("a", "f", 14), array("b", "c", 10), array("b", "d", 15), array("c", "d", 11), array("c", "f", 2), array("d", "e", 6), array("e", "f", 9) ); $path = dijkstra($graph_array, "a", "e"); echo "path is: ".implode(", ", $path)."\n";
package main import ( "container/heap" "fmt" ) type PriorityQueue struct { items []Vertex m map[Vertex]int pr map[Vertex]int } func (pq *PriorityQueue) Len() int { return len(pq.items) } func (pq *PriorityQueue) Less(i, j int) bool { return pq.pr[pq.items[i]] < pq.pr[pq.items[j]] } func (pq *PriorityQueue) Swap(i, j int) { pq.items[i], pq.items[j] = pq.items[j], pq.items[i] pq.m[pq.items[i]] = i pq.m[pq.items[j]] = j } func (pq *PriorityQueue) Push(x interface{}) { n := len(pq.items) item := x.(Vertex) pq.m[item] = n pq.items = append(pq.items, item) } func (pq *PriorityQueue) Pop() interface{} { old := pq.items n := len(old) item := old[n-1] pq.m[item] = -1 pq.items = old[0 : n-1] return item } func (pq *PriorityQueue) update(item Vertex, priority int) { pq.pr[item] = priority heap.Fix(pq, pq.m[item]) } func (pq *PriorityQueue) addWithPriority(item Vertex, priority int) { heap.Push(pq, item) pq.update(item, priority) } const ( Infinity = int(^uint(0) >> 1) Uninitialized = -1 ) func Dijkstra(g Graph, source Vertex) (dist map[Vertex]int, prev map[Vertex]Vertex) { vs := g.Vertices() dist = make(map[Vertex]int, len(vs)) prev = make(map[Vertex]Vertex, len(vs)) sid := source dist[sid] = 0 q := &PriorityQueue{ items: make([]Vertex, 0, len(vs)), m: make(map[Vertex]int, len(vs)), pr: make(map[Vertex]int, len(vs)), } for _, v := range vs { if v != sid { dist[v] = Infinity } prev[v] = Uninitialized q.addWithPriority(v, dist[v]) } for len(q.items) != 0 { u := heap.Pop(q).(Vertex) for _, v := range g.Neighbors(u) { alt := dist[u] + g.Weight(u, v) if alt < dist[v] { dist[v] = alt prev[v] = u q.update(v, alt) } } } return dist, prev } type Graph interface { Vertices() []Vertex Neighbors(v Vertex) []Vertex Weight(u, v Vertex) int } type Vertex int type sg struct { ids map[string]Vertex names map[Vertex]string edges map[Vertex]map[Vertex]int } func newsg(ids map[string]Vertex) sg { g := sg{ids: ids} g.names = make(map[Vertex]string, len(ids)) for k, v := range ids { g.names[v] = k } g.edges = make(map[Vertex]map[Vertex]int) return g } func (g sg) edge(u, v string, w int) { if _, ok := g.edges[g.ids[u]]; !ok { g.edges[g.ids[u]] = make(map[Vertex]int) } g.edges[g.ids[u]][g.ids[v]] = w } func (g sg) path(v Vertex, prev map[Vertex]Vertex) (s string) { s = g.names[v] for prev[v] >= 0 { v = prev[v] s = g.names[v] + s } return s } func (g sg) Vertices() []Vertex { vs := make([]Vertex, 0, len(g.ids)) for _, v := range g.ids { vs = append(vs, v) } return vs } func (g sg) Neighbors(u Vertex) []Vertex { vs := make([]Vertex, 0, len(g.edges[u])) for v := range g.edges[u] { vs = append(vs, v) } return vs } func (g sg) Weight(u, v Vertex) int { return g.edges[u][v] } func main() { g := newsg(map[string]Vertex{ "a": 1, "b": 2, "c": 3, "d": 4, "e": 5, "f": 6, }) g.edge("a", "b", 7) g.edge("a", "c", 9) g.edge("a", "f", 14) g.edge("b", "c", 10) g.edge("b", "d", 15) g.edge("c", "d", 11) g.edge("c", "f", 2) g.edge("d", "e", 6) g.edge("e", "f", 9) dist, prev := Dijkstra(g, g.ids["a"]) fmt.Printf("Distance to %s: %d, Path: %s\n", "e", dist[g.ids["e"]], g.path(g.ids["e"], prev)) fmt.Printf("Distance to %s: %d, Path: %s\n", "f", dist[g.ids["f"]], g.path(g.ids["f"], prev)) }
Write the same algorithm in Go as shown in this PHP implementation.
<?php function dijkstra($graph_array, $source, $target) { $vertices = array(); $neighbours = array(); foreach ($graph_array as $edge) { array_push($vertices, $edge[0], $edge[1]); $neighbours[$edge[0]][] = array("end" => $edge[1], "cost" => $edge[2]); $neighbours[$edge[1]][] = array("end" => $edge[0], "cost" => $edge[2]); } $vertices = array_unique($vertices); foreach ($vertices as $vertex) { $dist[$vertex] = INF; $previous[$vertex] = NULL; } $dist[$source] = 0; $Q = $vertices; while (count($Q) > 0) { $min = INF; foreach ($Q as $vertex){ if ($dist[$vertex] < $min) { $min = $dist[$vertex]; $u = $vertex; } } $Q = array_diff($Q, array($u)); if ($dist[$u] == INF or $u == $target) { break; } if (isset($neighbours[$u])) { foreach ($neighbours[$u] as $arr) { $alt = $dist[$u] + $arr["cost"]; if ($alt < $dist[$arr["end"]]) { $dist[$arr["end"]] = $alt; $previous[$arr["end"]] = $u; } } } } $path = array(); $u = $target; while (isset($previous[$u])) { array_unshift($path, $u); $u = $previous[$u]; } array_unshift($path, $u); return $path; } $graph_array = array( array("a", "b", 7), array("a", "c", 9), array("a", "f", 14), array("b", "c", 10), array("b", "d", 15), array("c", "d", 11), array("c", "f", 2), array("d", "e", 6), array("e", "f", 9) ); $path = dijkstra($graph_array, "a", "e"); echo "path is: ".implode(", ", $path)."\n";
package main import ( "container/heap" "fmt" ) type PriorityQueue struct { items []Vertex m map[Vertex]int pr map[Vertex]int } func (pq *PriorityQueue) Len() int { return len(pq.items) } func (pq *PriorityQueue) Less(i, j int) bool { return pq.pr[pq.items[i]] < pq.pr[pq.items[j]] } func (pq *PriorityQueue) Swap(i, j int) { pq.items[i], pq.items[j] = pq.items[j], pq.items[i] pq.m[pq.items[i]] = i pq.m[pq.items[j]] = j } func (pq *PriorityQueue) Push(x interface{}) { n := len(pq.items) item := x.(Vertex) pq.m[item] = n pq.items = append(pq.items, item) } func (pq *PriorityQueue) Pop() interface{} { old := pq.items n := len(old) item := old[n-1] pq.m[item] = -1 pq.items = old[0 : n-1] return item } func (pq *PriorityQueue) update(item Vertex, priority int) { pq.pr[item] = priority heap.Fix(pq, pq.m[item]) } func (pq *PriorityQueue) addWithPriority(item Vertex, priority int) { heap.Push(pq, item) pq.update(item, priority) } const ( Infinity = int(^uint(0) >> 1) Uninitialized = -1 ) func Dijkstra(g Graph, source Vertex) (dist map[Vertex]int, prev map[Vertex]Vertex) { vs := g.Vertices() dist = make(map[Vertex]int, len(vs)) prev = make(map[Vertex]Vertex, len(vs)) sid := source dist[sid] = 0 q := &PriorityQueue{ items: make([]Vertex, 0, len(vs)), m: make(map[Vertex]int, len(vs)), pr: make(map[Vertex]int, len(vs)), } for _, v := range vs { if v != sid { dist[v] = Infinity } prev[v] = Uninitialized q.addWithPriority(v, dist[v]) } for len(q.items) != 0 { u := heap.Pop(q).(Vertex) for _, v := range g.Neighbors(u) { alt := dist[u] + g.Weight(u, v) if alt < dist[v] { dist[v] = alt prev[v] = u q.update(v, alt) } } } return dist, prev } type Graph interface { Vertices() []Vertex Neighbors(v Vertex) []Vertex Weight(u, v Vertex) int } type Vertex int type sg struct { ids map[string]Vertex names map[Vertex]string edges map[Vertex]map[Vertex]int } func newsg(ids map[string]Vertex) sg { g := sg{ids: ids} g.names = make(map[Vertex]string, len(ids)) for k, v := range ids { g.names[v] = k } g.edges = make(map[Vertex]map[Vertex]int) return g } func (g sg) edge(u, v string, w int) { if _, ok := g.edges[g.ids[u]]; !ok { g.edges[g.ids[u]] = make(map[Vertex]int) } g.edges[g.ids[u]][g.ids[v]] = w } func (g sg) path(v Vertex, prev map[Vertex]Vertex) (s string) { s = g.names[v] for prev[v] >= 0 { v = prev[v] s = g.names[v] + s } return s } func (g sg) Vertices() []Vertex { vs := make([]Vertex, 0, len(g.ids)) for _, v := range g.ids { vs = append(vs, v) } return vs } func (g sg) Neighbors(u Vertex) []Vertex { vs := make([]Vertex, 0, len(g.edges[u])) for v := range g.edges[u] { vs = append(vs, v) } return vs } func (g sg) Weight(u, v Vertex) int { return g.edges[u][v] } func main() { g := newsg(map[string]Vertex{ "a": 1, "b": 2, "c": 3, "d": 4, "e": 5, "f": 6, }) g.edge("a", "b", 7) g.edge("a", "c", 9) g.edge("a", "f", 14) g.edge("b", "c", 10) g.edge("b", "d", 15) g.edge("c", "d", 11) g.edge("c", "f", 2) g.edge("d", "e", 6) g.edge("e", "f", 9) dist, prev := Dijkstra(g, g.ids["a"]) fmt.Printf("Distance to %s: %d, Path: %s\n", "e", dist[g.ids["e"]], g.path(g.ids["e"], prev)) fmt.Printf("Distance to %s: %d, Path: %s\n", "f", dist[g.ids["f"]], g.path(g.ids["f"], prev)) }
Rewrite the snippet below in Go so it works the same as the original PHP code.
<?php $pairs = array( "hello" => 1, "world" => 2, "!" => 3 ); foreach($pairs as $k => $v) { echo "(k,v) = ($k, $v)\n"; } foreach(array_keys($pairs) as $key) { echo "key = $key, value = $pairs[$key]\n"; } foreach($pairs as $value) { echo "values = $value\n"; } ?>
myMap := map[string]int { "hello": 13, "world": 31, "!" : 71 } for key, value := range myMap { fmt.Printf("key = %s, value = %d\n", key, value) } for key := range myMap { fmt.Printf("key = %s\n", key) } for _, value := range myMap { fmt.Printf("value = %d\n", value) }
Rewrite the snippet below in Go so it works the same as the original PHP code.
<?php $pairs = array( "hello" => 1, "world" => 2, "!" => 3 ); foreach($pairs as $k => $v) { echo "(k,v) = ($k, $v)\n"; } foreach(array_keys($pairs) as $key) { echo "key = $key, value = $pairs[$key]\n"; } foreach($pairs as $value) { echo "values = $value\n"; } ?>
myMap := map[string]int { "hello": 13, "world": 31, "!" : 71 } for key, value := range myMap { fmt.Printf("key = %s, value = %d\n", key, value) } for key := range myMap { fmt.Printf("key = %s\n", key) } for _, value := range myMap { fmt.Printf("value = %d\n", value) }
Translate the given PHP code snippet into Go without altering its behavior.
$address = <<<END 1, High Street, $town_name, West Midlands. WM4 5HD. END;
var m = ` leading spaces and blank lines`
Keep all operations the same but rewrite the snippet in Go.
$address = <<<END 1, High Street, $town_name, West Midlands. WM4 5HD. END;
var m = ` leading spaces and blank lines`
Rewrite this program in Go while keeping its functionality equivalent to the PHP version.
$address = <<<END 1, High Street, $town_name, West Midlands. WM4 5HD. END;
var m = ` leading spaces and blank lines`
Write the same code in Go as shown below in PHP.
$address = <<<END 1, High Street, $town_name, West Midlands. WM4 5HD. END;
var m = ` leading spaces and blank lines`
Transform the following PHP implementation into Go, maintaining the same output and logic.
<?php function hashJoin($table1, $index1, $table2, $index2) { foreach ($table1 as $s) $h[$s[$index1]][] = $s; foreach ($table2 as $r) foreach ($h[$r[$index2]] as $s) $result[] = array($s, $r); return $result; } $table1 = array(array(27, "Jonah"), array(18, "Alan"), array(28, "Glory"), array(18, "Popeye"), array(28, "Alan")); $table2 = array(array("Jonah", "Whales"), array("Jonah", "Spiders"), array("Alan", "Ghosts"), array("Alan", "Zombies"), array("Glory", "Buffy"), array("Bob", "foo")); foreach (hashJoin($table1, 1, $table2, 0) as $row) print_r($row); ?>
package main import "fmt" func main() { tableA := []struct { value int key string }{ {27, "Jonah"}, {18, "Alan"}, {28, "Glory"}, {18, "Popeye"}, {28, "Alan"}, } tableB := []struct { key string value string }{ {"Jonah", "Whales"}, {"Jonah", "Spiders"}, {"Alan", "Ghosts"}, {"Alan", "Zombies"}, {"Glory", "Buffy"}, } h := map[string][]int{} for i, r := range tableA { h[r.key] = append(h[r.key], i) } for _, x := range tableB { for _, a := range h[x.key] { fmt.Println(tableA[a], x) } } }
Generate an equivalent Go version of this PHP code.
<?php function hashJoin($table1, $index1, $table2, $index2) { foreach ($table1 as $s) $h[$s[$index1]][] = $s; foreach ($table2 as $r) foreach ($h[$r[$index2]] as $s) $result[] = array($s, $r); return $result; } $table1 = array(array(27, "Jonah"), array(18, "Alan"), array(28, "Glory"), array(18, "Popeye"), array(28, "Alan")); $table2 = array(array("Jonah", "Whales"), array("Jonah", "Spiders"), array("Alan", "Ghosts"), array("Alan", "Zombies"), array("Glory", "Buffy"), array("Bob", "foo")); foreach (hashJoin($table1, 1, $table2, 0) as $row) print_r($row); ?>
package main import "fmt" func main() { tableA := []struct { value int key string }{ {27, "Jonah"}, {18, "Alan"}, {28, "Glory"}, {18, "Popeye"}, {28, "Alan"}, } tableB := []struct { key string value string }{ {"Jonah", "Whales"}, {"Jonah", "Spiders"}, {"Alan", "Ghosts"}, {"Alan", "Zombies"}, {"Glory", "Buffy"}, } h := map[string][]int{} for i, r := range tableA { h[r.key] = append(h[r.key], i) } for _, x := range tableB { for _, a := range h[x.key] { fmt.Println(tableA[a], x) } } }
Translate the given PHP code snippet into Go without altering its behavior.
<?php class Example { function foo() { echo "this is foo\n"; } function bar() { echo "this is bar\n"; } function __call($name, $args) { echo "tried to handle unknown method $name\n"; if ($args) echo "it had arguments: ", implode(', ', $args), "\n"; } } $example = new Example(); $example->foo(); // prints "this is foo" $example->bar(); // prints "this is bar" $example->grill(); // prints "tried to handle unknown method grill" $example->ding("dong"); // prints "tried to handle unknown method ding" ?>
package main import ( "fmt" "reflect" ) type example struct{} func (example) Foo() int { return 42 } func (e example) CallMethod(n string) int { if m := reflect.ValueOf(e).MethodByName(n); m.IsValid() { return int(m.Call(nil)[0].Int()) } fmt.Println("Unknown method:", n) return 0 } func main() { var e example fmt.Println(e.CallMethod("Foo")) fmt.Println(e.CallMethod("Bar")) }
Rewrite the snippet below in Go so it works the same as the original PHP code.
<?php class Example { function foo() { echo "this is foo\n"; } function bar() { echo "this is bar\n"; } function __call($name, $args) { echo "tried to handle unknown method $name\n"; if ($args) echo "it had arguments: ", implode(', ', $args), "\n"; } } $example = new Example(); $example->foo(); // prints "this is foo" $example->bar(); // prints "this is bar" $example->grill(); // prints "tried to handle unknown method grill" $example->ding("dong"); // prints "tried to handle unknown method ding" ?>
package main import ( "fmt" "reflect" ) type example struct{} func (example) Foo() int { return 42 } func (e example) CallMethod(n string) int { if m := reflect.ValueOf(e).MethodByName(n); m.IsValid() { return int(m.Call(nil)[0].Int()) } fmt.Println("Unknown method:", n) return 0 } func main() { var e example fmt.Println(e.CallMethod("Foo")) fmt.Println(e.CallMethod("Bar")) }
Convert this PHP snippet to Go and keep its semantics consistent.
class Animal { } class Dog extends Animal { } class Cat extends Animal { } class Lab extends Dog { } class Collie extends Dog { }
package main type animal struct { alive bool } type dog struct { animal obedienceTrained bool } type cat struct { animal litterBoxTrained bool } type lab struct { dog color string } type collie struct { dog catchesFrisbee bool } func main() { var pet lab pet.alive = true pet.obedienceTrained = false pet.color = "yellow" }
Can you help me rewrite this code in Go instead of PHP, keeping it the same logically?
class Animal { } class Dog extends Animal { } class Cat extends Animal { } class Lab extends Dog { } class Collie extends Dog { }
package main type animal struct { alive bool } type dog struct { animal obedienceTrained bool } type cat struct { animal litterBoxTrained bool } type lab struct { dog color string } type collie struct { dog catchesFrisbee bool } func main() { var pet lab pet.alive = true pet.obedienceTrained = false pet.color = "yellow" }
Produce a language-to-language conversion: from PHP to Go, same semantics.
$array = array(); $array = []; // Simpler form of array initialization $array['foo'] = 'bar'; $array['bar'] = 'foo'; echo($array['foo']); // bar echo($array['moo']); // Undefined index $array2 = array('fruit' => 'apple', 'price' => 12.96, 'colour' => 'green'); $array2 = ['fruit' => 'apple', 'price' => 12.96, 'colour' => 'green']; echo(isset($array['foo'])); // Faster, but returns false if the value of the element is set to null echo(array_key_exists('foo', $array)); // Slower, but returns true if the value of the element is null
var x map[string]int x = make(map[string]int) x = make(map[string]int, 42) x["foo"] = 3 y1 := x["bar"] y2, ok := x["bar"] delete(x, "foo") x = map[string]int{ "foo": 2, "bar": 42, "baz": -1, }
Rewrite this program in Go while keeping its functionality equivalent to the PHP version.
$array = array(); $array = []; // Simpler form of array initialization $array['foo'] = 'bar'; $array['bar'] = 'foo'; echo($array['foo']); // bar echo($array['moo']); // Undefined index $array2 = array('fruit' => 'apple', 'price' => 12.96, 'colour' => 'green'); $array2 = ['fruit' => 'apple', 'price' => 12.96, 'colour' => 'green']; echo(isset($array['foo'])); // Faster, but returns false if the value of the element is set to null echo(array_key_exists('foo', $array)); // Slower, but returns true if the value of the element is null
var x map[string]int x = make(map[string]int) x = make(map[string]int, 42) x["foo"] = 3 y1 := x["bar"] y2, ok := x["bar"] delete(x, "foo") x = map[string]int{ "foo": 2, "bar": 42, "baz": -1, }
Convert the following code from PHP to Go, ensuring the logic remains intact.
class Point { protected $_x; protected $_y; public function __construct() { switch( func_num_args() ) { case 1: $point = func_get_arg( 0 ); $this->setFromPoint( $point ); break; case 2: $x = func_get_arg( 0 ); $y = func_get_arg( 1 ); $this->setX( $x ); $this->setY( $y ); break; default: throw new InvalidArgumentException( 'expecting one (Point) argument or two (numeric x and y) arguments' ); } } public function setFromPoint( Point $point ) { $this->setX( $point->getX() ); $this->setY( $point->getY() ); } public function getX() { return $this->_x; } public function setX( $x ) { if( !is_numeric( $x ) ) { throw new InvalidArgumentException( 'expecting numeric value' ); } $this->_x = (float) $x; } public function getY() { return $this->_y; } public function setY( $y ) { if( !is_numeric( $y ) ) { throw new InvalidArgumentException( 'expecting numeric value' ); } $this->_y = (float) $y; } public function output() { echo $this->__toString(); } public function __toString() { return 'Point [x:' . $this->_x . ',y:' . $this->_y . ']'; } }
package main import "fmt" type point struct { x, y float64 } type circle struct { x, y, r float64 } type printer interface { print() } func (p *point) print() { fmt.Println(p.x, p.y) } func (c *circle) print() { fmt.Println(c.x, c.y, c.r) } func main() { var i printer i = newPoint(3, 4) i.print() i = newCircle(5, 12, 13) i.print() } func (p *point) getX() float64 { return p.x } func (p *point) getY() float64 { return p.y } func (p *point) setX(v float64) { p.x = v } func (p *point) setY(v float64) { p.y = v } func (c *circle) getX() float64 { return c.x } func (c *circle) getY() float64 { return c.y } func (c *circle) getR() float64 { return c.r } func (c *circle) setX(v float64) { c.x = v } func (c *circle) setY(v float64) { c.y = v } func (c *circle) setR(v float64) { c.r = v } func (p *point) clone() *point { r := *p; return &r } func (c *circle) clone() *circle { r := *c; return &r } func (p *point) set(q *point) { *p = *q } func (c *circle) set(d *circle) { *c = *d } func newPoint(x, y float64) *point { return &point{x, y} } func newCircle(x, y, r float64) *circle { return &circle{x, y, r} }
Change the following PHP code into Go without altering its purpose.
class Point { protected $_x; protected $_y; public function __construct() { switch( func_num_args() ) { case 1: $point = func_get_arg( 0 ); $this->setFromPoint( $point ); break; case 2: $x = func_get_arg( 0 ); $y = func_get_arg( 1 ); $this->setX( $x ); $this->setY( $y ); break; default: throw new InvalidArgumentException( 'expecting one (Point) argument or two (numeric x and y) arguments' ); } } public function setFromPoint( Point $point ) { $this->setX( $point->getX() ); $this->setY( $point->getY() ); } public function getX() { return $this->_x; } public function setX( $x ) { if( !is_numeric( $x ) ) { throw new InvalidArgumentException( 'expecting numeric value' ); } $this->_x = (float) $x; } public function getY() { return $this->_y; } public function setY( $y ) { if( !is_numeric( $y ) ) { throw new InvalidArgumentException( 'expecting numeric value' ); } $this->_y = (float) $y; } public function output() { echo $this->__toString(); } public function __toString() { return 'Point [x:' . $this->_x . ',y:' . $this->_y . ']'; } }
package main import "fmt" type point struct { x, y float64 } type circle struct { x, y, r float64 } type printer interface { print() } func (p *point) print() { fmt.Println(p.x, p.y) } func (c *circle) print() { fmt.Println(c.x, c.y, c.r) } func main() { var i printer i = newPoint(3, 4) i.print() i = newCircle(5, 12, 13) i.print() } func (p *point) getX() float64 { return p.x } func (p *point) getY() float64 { return p.y } func (p *point) setX(v float64) { p.x = v } func (p *point) setY(v float64) { p.y = v } func (c *circle) getX() float64 { return c.x } func (c *circle) getY() float64 { return c.y } func (c *circle) getR() float64 { return c.r } func (c *circle) setX(v float64) { c.x = v } func (c *circle) setY(v float64) { c.y = v } func (c *circle) setR(v float64) { c.r = v } func (p *point) clone() *point { r := *p; return &r } func (c *circle) clone() *circle { r := *c; return &r } func (p *point) set(q *point) { *p = *q } func (c *circle) set(d *circle) { *c = *d } func newPoint(x, y float64) *point { return &point{x, y} } func newCircle(x, y, r float64) *circle { return &circle{x, y, r} }
Produce a language-to-language conversion: from PHP to Go, same semantics.
<? class Foo { } $obj = new Foo(); $obj->bar = 42; $obj->baz = true; var_dump(get_object_vars($obj)); ?>
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() }
Produce a functionally identical Go code for the snippet given in PHP.
<? class Foo { } $obj = new Foo(); $obj->bar = 42; $obj->baz = true; var_dump(get_object_vars($obj)); ?>
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() }
Maintain the same structure and functionality when rewriting this code in Go.
<?php $j2justtype = array('L' => STR_PAD_RIGHT, 'R' => STR_PAD_LEFT, 'C' => STR_PAD_BOTH); function aligner($str, $justification = 'L') { global $j2justtype; assert(array_key_exists($justification, $j2justtype)); $justtype = $j2justtype[$justification]; $fieldsbyrow = array(); foreach (explode("\n", $str) as $line) $fieldsbyrow[] = explode('$', $line); $maxfields = max(array_map('count', $fieldsbyrow)); foreach (range(0, $maxfields - 1) as $col) { $maxwidth = 0; foreach ($fieldsbyrow as $fields) $maxwidth = max($maxwidth, strlen(array_key_exists($col, $fields) ? $fields[$col] : 0)); foreach ($fieldsbyrow as &$fields) $fields[$col] = str_pad(array_key_exists($col, $fields) ? $fields[$col] : "", $maxwidth, ' ', $justtype); unset($fields); // see http://bugs.php.net/29992 } $result = ''; foreach ($fieldsbyrow as $fields) $result .= implode(' ', $fields) . "\n"; return $result; } $textinfile = 'Given$a$text$file$of$many$lines,$where$fields$within$a$line$ are$delineated$by$a$single$\'dollar\'$character,$write$a$program that$aligns$each$column$of$fields$by$ensuring$that$words$in$each$ column$are$separated$by$at$least$one$space. Further,$allow$for$each$word$in$a$column$to$be$either$left$ justified,$right$justified,$or$center$justified$within$its$column.'; foreach (array('L', 'R', 'C') as $j) echo aligner($textinfile, $j); ?>
package main import ( "fmt" "strings" ) const text = `Given$a$text$file$of$many$lines,$where$fields$within$a$line$ are$delineated$by$a$single$'dollar'$character,$write$a$program that$aligns$each$column$of$fields$by$ensuring$that$words$in$each$ column$are$separated$by$at$least$one$space. Further,$allow$for$each$word$in$a$column$to$be$either$left$ justified,$right$justified,$or$center$justified$within$its$column.` type formatter struct { text [][]string width []int } func newFormatter(text string) *formatter { var f formatter for _, line := range strings.Split(text, "\n") { words := strings.Split(line, "$") for words[len(words)-1] == "" { words = words[:len(words)-1] } f.text = append(f.text, words) for i, word := range words { if i == len(f.width) { f.width = append(f.width, len(word)) } else if len(word) > f.width[i] { f.width[i] = len(word) } } } return &f } const ( left = iota middle right ) func (f formatter) print(j int) { for _, line := range f.text { for i, word := range line { fmt.Printf("%-*s ", f.width[i], fmt.Sprintf("%*s", len(word)+(f.width[i]-len(word))*j/2, word)) } fmt.Println("") } fmt.Println("") } func main() { f := newFormatter(text) f.print(left) f.print(middle) f.print(right) }
Write a version of this PHP function in Go with identical behavior.
<?php $j2justtype = array('L' => STR_PAD_RIGHT, 'R' => STR_PAD_LEFT, 'C' => STR_PAD_BOTH); function aligner($str, $justification = 'L') { global $j2justtype; assert(array_key_exists($justification, $j2justtype)); $justtype = $j2justtype[$justification]; $fieldsbyrow = array(); foreach (explode("\n", $str) as $line) $fieldsbyrow[] = explode('$', $line); $maxfields = max(array_map('count', $fieldsbyrow)); foreach (range(0, $maxfields - 1) as $col) { $maxwidth = 0; foreach ($fieldsbyrow as $fields) $maxwidth = max($maxwidth, strlen(array_key_exists($col, $fields) ? $fields[$col] : 0)); foreach ($fieldsbyrow as &$fields) $fields[$col] = str_pad(array_key_exists($col, $fields) ? $fields[$col] : "", $maxwidth, ' ', $justtype); unset($fields); // see http://bugs.php.net/29992 } $result = ''; foreach ($fieldsbyrow as $fields) $result .= implode(' ', $fields) . "\n"; return $result; } $textinfile = 'Given$a$text$file$of$many$lines,$where$fields$within$a$line$ are$delineated$by$a$single$\'dollar\'$character,$write$a$program that$aligns$each$column$of$fields$by$ensuring$that$words$in$each$ column$are$separated$by$at$least$one$space. Further,$allow$for$each$word$in$a$column$to$be$either$left$ justified,$right$justified,$or$center$justified$within$its$column.'; foreach (array('L', 'R', 'C') as $j) echo aligner($textinfile, $j); ?>
package main import ( "fmt" "strings" ) const text = `Given$a$text$file$of$many$lines,$where$fields$within$a$line$ are$delineated$by$a$single$'dollar'$character,$write$a$program that$aligns$each$column$of$fields$by$ensuring$that$words$in$each$ column$are$separated$by$at$least$one$space. Further,$allow$for$each$word$in$a$column$to$be$either$left$ justified,$right$justified,$or$center$justified$within$its$column.` type formatter struct { text [][]string width []int } func newFormatter(text string) *formatter { var f formatter for _, line := range strings.Split(text, "\n") { words := strings.Split(line, "$") for words[len(words)-1] == "" { words = words[:len(words)-1] } f.text = append(f.text, words) for i, word := range words { if i == len(f.width) { f.width = append(f.width, len(word)) } else if len(word) > f.width[i] { f.width[i] = len(word) } } } return &f } const ( left = iota middle right ) func (f formatter) print(j int) { for _, line := range f.text { for i, word := range line { fmt.Printf("%-*s ", f.width[i], fmt.Sprintf("%*s", len(word)+(f.width[i]-len(word))*j/2, word)) } fmt.Println("") } fmt.Println("") } func main() { f := newFormatter(text) f.print(left) f.print(middle) f.print(right) }
Keep all operations the same but rewrite the snippet in Go.
<?php $urls = array( 'foo://example.com:8042/over/there?name=ferret#nose', 'urn:example:animal:ferret:nose', 'jdbc:mysql://test_user:ouupppssss@localhost:3306/sakila?profileSQL=true', 'ftp://ftp.is.co.za/rfc/rfc1808.txt', 'http://www.ietf.org/rfc/rfc2396.txt#header1', 'ldap://[2001:db8::7]/c=GB?objectClass=one&objectClass=two', 'mailto:John.Doe@example.com', 'news:comp.infosystems.www.servers.unix', 'tel:+1-816-555-1212', 'telnet://192.0.2.16:80/', 'urn:oasis:names:specification:docbook:dtd:xml:4.1.2', ); foreach ($urls AS $url) { $p = parse_url($url); echo $url, PHP_EOL; print_r($p); echo PHP_EOL; }
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) } }
Generate a Go translation of this PHP snippet without changing its computational steps.
<?php $urls = array( 'foo://example.com:8042/over/there?name=ferret#nose', 'urn:example:animal:ferret:nose', 'jdbc:mysql://test_user:ouupppssss@localhost:3306/sakila?profileSQL=true', 'ftp://ftp.is.co.za/rfc/rfc1808.txt', 'http://www.ietf.org/rfc/rfc2396.txt#header1', 'ldap://[2001:db8::7]/c=GB?objectClass=one&objectClass=two', 'mailto:John.Doe@example.com', 'news:comp.infosystems.www.servers.unix', 'tel:+1-816-555-1212', 'telnet://192.0.2.16:80/', 'urn:oasis:names:specification:docbook:dtd:xml:4.1.2', ); foreach ($urls AS $url) { $p = parse_url($url); echo $url, PHP_EOL; print_r($p); echo PHP_EOL; }
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) } }
Convert this PHP block to Go, preserving its control flow and logic.
<?php $urls = array( 'foo://example.com:8042/over/there?name=ferret#nose', 'urn:example:animal:ferret:nose', 'jdbc:mysql://test_user:ouupppssss@localhost:3306/sakila?profileSQL=true', 'ftp://ftp.is.co.za/rfc/rfc1808.txt', 'http://www.ietf.org/rfc/rfc2396.txt#header1', 'ldap://[2001:db8::7]/c=GB?objectClass=one&objectClass=two', 'mailto:John.Doe@example.com', 'news:comp.infosystems.www.servers.unix', 'tel:+1-816-555-1212', 'telnet://192.0.2.16:80/', 'urn:oasis:names:specification:docbook:dtd:xml:4.1.2', ); foreach ($urls AS $url) { $p = parse_url($url); echo $url, PHP_EOL; print_r($p); echo PHP_EOL; }
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) } }
Translate this program into Go but keep the logic exactly as in PHP.
<?php $urls = array( 'foo://example.com:8042/over/there?name=ferret#nose', 'urn:example:animal:ferret:nose', 'jdbc:mysql://test_user:ouupppssss@localhost:3306/sakila?profileSQL=true', 'ftp://ftp.is.co.za/rfc/rfc1808.txt', 'http://www.ietf.org/rfc/rfc2396.txt#header1', 'ldap://[2001:db8::7]/c=GB?objectClass=one&objectClass=two', 'mailto:John.Doe@example.com', 'news:comp.infosystems.www.servers.unix', 'tel:+1-816-555-1212', 'telnet://192.0.2.16:80/', 'urn:oasis:names:specification:docbook:dtd:xml:4.1.2', ); foreach ($urls AS $url) { $p = parse_url($url); echo $url, PHP_EOL; print_r($p); echo PHP_EOL; }
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) } }
Port the provided PHP code into Go while preserving the original functionality.
<?php $varname = rtrim(fgets(STDIN)); # type in "foo" on standard input $$varname = 42; echo "$foo\n"; # prints "42" ?>
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) } } }
Translate this program into Go but keep the logic exactly as in PHP.
<?php $varname = rtrim(fgets(STDIN)); # type in "foo" on standard input $$varname = 42; echo "$foo\n"; # prints "42" ?>
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) } } }
Change the following PHP code into Go without altering its purpose.
<? class Foo { function bar(int $x) { } } $method_names = get_class_methods('Foo'); foreach ($method_names as $name) { echo "$name\n"; $method_info = new ReflectionMethod('Foo', $name); echo $method_info; } ?>
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() }
Can you help me rewrite this code in Go instead of PHP, keeping it the same logically?
<? class Foo { function bar(int $x) { } } $method_names = get_class_methods('Foo'); foreach ($method_names as $name) { echo "$name\n"; $method_info = new ReflectionMethod('Foo', $name); echo $method_info; } ?>
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() }
Change the programming language of this snippet from PHP to Go without modifying what it does.
<?php class Example { function foo($x) { return 42 + $x; } } $example = new Example(); $name = 'foo'; echo $example->$name(5), "\n"; // prints "47" echo call_user_func(array($example, $name), 5), "\n"; ?>
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()) }
Maintain the same structure and functionality when rewriting this code in Go.
<?php class Example { function foo($x) { return 42 + $x; } } $example = new Example(); $name = 'foo'; echo $example->$name(5), "\n"; // prints "47" echo call_user_func(array($example, $name), 5), "\n"; ?>
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()) }
Port the provided PHP code into Go while preserving the original functionality.
<?php # NULL typed variable $null = NULL; var_dump($null); // output: null # defining a boolean $boolean = true; var_dump($boolean); // output: boolean true $boolean = false; var_dump($boolean); // output: boolean false # bool and boolean is the same $boolean = (bool)1; var_dump($boolean); // output: boolean true $boolean = (boolean)1; var_dump($boolean); // output: boolean true $boolean = (bool)0; var_dump($boolean); // output: boolean false $boolean = (boolean)0; var_dump($boolean); // output: boolean false # defining an integer $int = 0; var_dump($int); // output: int 0 # defining a float, $float = 0.01; var_dump($float); // output: float 0.01 # which is also identical to "real" and "double" var_dump((double)$float); // output: float 0.01 var_dump((real)$float); // output: float 0.01 # casting back to int (auto flooring the value) var_dump((int)$float); // output: int 0 var_dump((int)($float+1)); // output: int 1 var_dump((int)($float+1.9)); // output: int 1 # defining a string $string = 'string'; var_dump($string); // output: string 'string' (length=6) # referencing a variable (there are no pointers in PHP). $another_string = &$string; var_dump($another_string); $string = "I'm the same string!"; var_dump($another_string); # "deleting" a variable from memory unset($another_string); $string = 'string'; $parsed_string = "This is a $string"; var_dump($parsed_string); $parsed_string .= " with another {$string}"; var_dump($parsed_string); # with string parsing $heredoc = <<<HEREDOC This is the content of \$string: {$string} HEREDOC; var_dump($heredoc); # without string parsing (notice the single quotes surrounding NOWDOC) $nowdoc = <<<'NOWDOC' This is the content of \$string: {$string} NOWDOC; var_dump($nowdoc); # as of PHP5, defining an object typed stdClass => standard class $stdObject = new stdClass(); var_dump($stdObject); # defining an object typed Foo class Foo {} $foo = new Foo(); var_dump($foo); # defining an empty array $array = array(); var_dump($array); $assoc = array( 0 => $int, 'integer' => $int, 1 => $float, 'float' => $float, 2 => $string, 'string' => $string, 3 => NULL, // <=== key 3 is NULL 3, // <=== this is a value, not a key (key is 4) 5 => $stdObject, 'Foo' => $foo, ); var_dump($assoc); function a_function() { # not reachable var_dump(isset($foo)); // output: boolean false global $foo; # "global" (reachable) inside a_function()'s scope var_dump(isset($foo)); // output: boolean true } a_function();
x := 3
Change the following PHP code into Go without altering its purpose.
<?php # NULL typed variable $null = NULL; var_dump($null); // output: null # defining a boolean $boolean = true; var_dump($boolean); // output: boolean true $boolean = false; var_dump($boolean); // output: boolean false # bool and boolean is the same $boolean = (bool)1; var_dump($boolean); // output: boolean true $boolean = (boolean)1; var_dump($boolean); // output: boolean true $boolean = (bool)0; var_dump($boolean); // output: boolean false $boolean = (boolean)0; var_dump($boolean); // output: boolean false # defining an integer $int = 0; var_dump($int); // output: int 0 # defining a float, $float = 0.01; var_dump($float); // output: float 0.01 # which is also identical to "real" and "double" var_dump((double)$float); // output: float 0.01 var_dump((real)$float); // output: float 0.01 # casting back to int (auto flooring the value) var_dump((int)$float); // output: int 0 var_dump((int)($float+1)); // output: int 1 var_dump((int)($float+1.9)); // output: int 1 # defining a string $string = 'string'; var_dump($string); // output: string 'string' (length=6) # referencing a variable (there are no pointers in PHP). $another_string = &$string; var_dump($another_string); $string = "I'm the same string!"; var_dump($another_string); # "deleting" a variable from memory unset($another_string); $string = 'string'; $parsed_string = "This is a $string"; var_dump($parsed_string); $parsed_string .= " with another {$string}"; var_dump($parsed_string); # with string parsing $heredoc = <<<HEREDOC This is the content of \$string: {$string} HEREDOC; var_dump($heredoc); # without string parsing (notice the single quotes surrounding NOWDOC) $nowdoc = <<<'NOWDOC' This is the content of \$string: {$string} NOWDOC; var_dump($nowdoc); # as of PHP5, defining an object typed stdClass => standard class $stdObject = new stdClass(); var_dump($stdObject); # defining an object typed Foo class Foo {} $foo = new Foo(); var_dump($foo); # defining an empty array $array = array(); var_dump($array); $assoc = array( 0 => $int, 'integer' => $int, 1 => $float, 'float' => $float, 2 => $string, 'string' => $string, 3 => NULL, // <=== key 3 is NULL 3, // <=== this is a value, not a key (key is 4) 5 => $stdObject, 'Foo' => $foo, ); var_dump($assoc); function a_function() { # not reachable var_dump(isset($foo)); // output: boolean false global $foo; # "global" (reachable) inside a_function()'s scope var_dump(isset($foo)); // output: boolean true } a_function();
x := 3
Write a version of this PHP function in Go with identical behavior.
<?php function eval_with_x($code, $a, $b) { $x = $a; $first = eval($code); $x = $b; $second = eval($code); return $second - $first; } echo eval_with_x('return 3 * $x;', 5, 10), "\n"; # Prints "15". ?>
package main import ( "bitbucket.org/binet/go-eval/pkg/eval" "fmt" "go/parser" "go/token" ) func main() { squareExpr := "x*x" fset := token.NewFileSet() squareAst, err := parser.ParseExpr(squareExpr) if err != nil { fmt.Println(err) return } w := eval.NewWorld() wVar := new(intV) err = w.DefineVar("x", eval.IntType, wVar) if err != nil { fmt.Println(err) return } squareCode, err := w.CompileExpr(fset, squareAst) if err != nil { fmt.Println(err) return } *wVar = 5 r0, err := squareCode.Run() if err != nil { fmt.Println(err) return } *wVar-- r1, err := squareCode.Run() if err != nil { fmt.Println(err) return } fmt.Println(r0.(eval.IntValue).Get(nil) - r1.(eval.IntValue).Get(nil)) } type intV int64 func (v *intV) String() string { return fmt.Sprint(*v) } func (v *intV) Get(*eval.Thread) int64 { return int64(*v) } func (v *intV) Set(_ *eval.Thread, x int64) { *v = intV(x) } func (v *intV) Assign(t *eval.Thread, o eval.Value) { *v = intV(o.(eval.IntValue).Get(t)) }
Ensure the translated Go code behaves exactly like the original PHP snippet.
<?php function eval_with_x($code, $a, $b) { $x = $a; $first = eval($code); $x = $b; $second = eval($code); return $second - $first; } echo eval_with_x('return 3 * $x;', 5, 10), "\n"; # Prints "15". ?>
package main import ( "bitbucket.org/binet/go-eval/pkg/eval" "fmt" "go/parser" "go/token" ) func main() { squareExpr := "x*x" fset := token.NewFileSet() squareAst, err := parser.ParseExpr(squareExpr) if err != nil { fmt.Println(err) return } w := eval.NewWorld() wVar := new(intV) err = w.DefineVar("x", eval.IntType, wVar) if err != nil { fmt.Println(err) return } squareCode, err := w.CompileExpr(fset, squareAst) if err != nil { fmt.Println(err) return } *wVar = 5 r0, err := squareCode.Run() if err != nil { fmt.Println(err) return } *wVar-- r1, err := squareCode.Run() if err != nil { fmt.Println(err) return } fmt.Println(r0.(eval.IntValue).Get(nil) - r1.(eval.IntValue).Get(nil)) } type intV int64 func (v *intV) String() string { return fmt.Sprint(*v) } func (v *intV) Get(*eval.Thread) int64 { return int64(*v) } func (v *intV) Set(_ *eval.Thread, x int64) { *v = intV(x) } func (v *intV) Assign(t *eval.Thread, o eval.Value) { *v = intV(o.(eval.IntValue).Get(t)) }
Change the following PHP code into Go without altering its purpose.
<?php function eval_with_x($code, $a, $b) { $x = $a; $first = eval($code); $x = $b; $second = eval($code); return $second - $first; } echo eval_with_x('return 3 * $x;', 5, 10), "\n"; # Prints "15". ?>
package main import ( "bitbucket.org/binet/go-eval/pkg/eval" "fmt" "go/parser" "go/token" ) func main() { squareExpr := "x*x" fset := token.NewFileSet() squareAst, err := parser.ParseExpr(squareExpr) if err != nil { fmt.Println(err) return } w := eval.NewWorld() wVar := new(intV) err = w.DefineVar("x", eval.IntType, wVar) if err != nil { fmt.Println(err) return } squareCode, err := w.CompileExpr(fset, squareAst) if err != nil { fmt.Println(err) return } *wVar = 5 r0, err := squareCode.Run() if err != nil { fmt.Println(err) return } *wVar-- r1, err := squareCode.Run() if err != nil { fmt.Println(err) return } fmt.Println(r0.(eval.IntValue).Get(nil) - r1.(eval.IntValue).Get(nil)) } type intV int64 func (v *intV) String() string { return fmt.Sprint(*v) } func (v *intV) Get(*eval.Thread) int64 { return int64(*v) } func (v *intV) Set(_ *eval.Thread, x int64) { *v = intV(x) } func (v *intV) Assign(t *eval.Thread, o eval.Value) { *v = intV(o.(eval.IntValue).Get(t)) }
Keep all operations the same but rewrite the snippet in Go.
<?php function eval_with_x($code, $a, $b) { $x = $a; $first = eval($code); $x = $b; $second = eval($code); return $second - $first; } echo eval_with_x('return 3 * $x;', 5, 10), "\n"; # Prints "15". ?>
package main import ( "bitbucket.org/binet/go-eval/pkg/eval" "fmt" "go/parser" "go/token" ) func main() { squareExpr := "x*x" fset := token.NewFileSet() squareAst, err := parser.ParseExpr(squareExpr) if err != nil { fmt.Println(err) return } w := eval.NewWorld() wVar := new(intV) err = w.DefineVar("x", eval.IntType, wVar) if err != nil { fmt.Println(err) return } squareCode, err := w.CompileExpr(fset, squareAst) if err != nil { fmt.Println(err) return } *wVar = 5 r0, err := squareCode.Run() if err != nil { fmt.Println(err) return } *wVar-- r1, err := squareCode.Run() if err != nil { fmt.Println(err) return } fmt.Println(r0.(eval.IntValue).Get(nil) - r1.(eval.IntValue).Get(nil)) } type intV int64 func (v *intV) String() string { return fmt.Sprint(*v) } func (v *intV) Get(*eval.Thread) int64 { return int64(*v) } func (v *intV) Set(_ *eval.Thread, x int64) { *v = intV(x) } func (v *intV) Assign(t *eval.Thread, o eval.Value) { *v = intV(o.(eval.IntValue).Get(t)) }
Can you help me rewrite this code in Go instead of PHP, keeping it the same logically?
<?php $code = 'echo "hello world"'; eval($code); $code = 'return "hello world"'; print eval($code);
package main import ( "fmt" "bitbucket.org/binet/go-eval/pkg/eval" "go/token" ) func main() { w := eval.NewWorld(); fset := token.NewFileSet(); code, err := w.Compile(fset, "1 + 2") if err != nil { fmt.Println("Compile error"); return } val, err := code.Run(); if err != nil { fmt.Println("Run time error"); return; } fmt.Println("Return value:", val) }
Convert this PHP block to Go, preserving its control flow and logic.
<?php $code = 'echo "hello world"'; eval($code); $code = 'return "hello world"'; print eval($code);
package main import ( "fmt" "bitbucket.org/binet/go-eval/pkg/eval" "go/token" ) func main() { w := eval.NewWorld(); fset := token.NewFileSet(); code, err := w.Compile(fset, "1 + 2") if err != nil { fmt.Println("Compile error"); return } val, err := code.Run(); if err != nil { fmt.Println("Run time error"); return; } fmt.Println("Return value:", val) }
Port the following code from PHP to Go with equivalent syntax and logic.
<?php $code = 'echo "hello world"'; eval($code); $code = 'return "hello world"'; print eval($code);
package main import ( "fmt" "bitbucket.org/binet/go-eval/pkg/eval" "go/token" ) func main() { w := eval.NewWorld(); fset := token.NewFileSet(); code, err := w.Compile(fset, "1 + 2") if err != nil { fmt.Println("Compile error"); return } val, err := code.Run(); if err != nil { fmt.Println("Run time error"); return; } fmt.Println("Return value:", val) }