Instruction
stringlengths
45
106
input_code
stringlengths
1
13.7k
output_code
stringlengths
1
13.7k
Write a version of this R function in Python with identical behavior.
x <- list(list(1), 2, list(list(3, 4), 5), list(list(list())), list(list(list(6))), 7, 8, list()) unlist(x)
>>> def flatten(lst): return sum( ([x] if not isinstance(x, list) else flatten(x) for x in lst), [] ) >>> lst = [[1], 2, [[3,4], 5], [[[]]], [[[6]]], 7, 8, []] >>> flatten(lst) [1, 2, 3, 4, 5, 6, 7, 8]
Rewrite this program in VB while keeping its functionality equivalent to the R version.
x <- list(list(1), 2, list(list(3, 4), 5), list(list(list())), list(list(list(6))), 7, 8, list()) unlist(x)
class flattener dim separator sub class_initialize separator = "," end sub private function makeflat( a ) dim i dim res for i = lbound( a ) to ubound( a ) if isarray( a( i ) ) then res = res & makeflat( a( i ) ) else res = res & a( i ) & separator end if next makeflat = res end function public function flatten( a ) dim res res = makeflat( a ) res = left( res, len( res ) - len(separator)) res = split( res, separator ) flatten = res end function public property let itemSeparator( c ) separator = c end property end class
Translate the given R code snippet into VB without altering its behavior.
x <- list(list(1), 2, list(list(3, 4), 5), list(list(list())), list(list(list(6))), 7, 8, list()) unlist(x)
class flattener dim separator sub class_initialize separator = "," end sub private function makeflat( a ) dim i dim res for i = lbound( a ) to ubound( a ) if isarray( a( i ) ) then res = res & makeflat( a( i ) ) else res = res & a( i ) & separator end if next makeflat = res end function public function flatten( a ) dim res res = makeflat( a ) res = left( res, len( res ) - len(separator)) res = split( res, separator ) flatten = res end function public property let itemSeparator( c ) separator = c end property end class
Convert this R snippet to Go and keep its semantics consistent.
x <- list(list(1), 2, list(list(3, 4), 5), list(list(list())), list(list(list(6))), 7, 8, list()) unlist(x)
package main import "fmt" func list(s ...interface{}) []interface{} { return s } func main() { s := list(list(1), 2, list(list(3, 4), 5), list(list(list())), list(list(list(6))), 7, 8, list(), ) fmt.Println(s) fmt.Println(flatten(s)) } func flatten(s []interface{}) (r []int) { for _, e := range s { switch i := e.(type) { case int: r = append(r, i) case []interface{}: r = append(r, flatten(i)...) } } return }
Transform the following R implementation into Go, maintaining the same output and logic.
x <- list(list(1), 2, list(list(3, 4), 5), list(list(list())), list(list(list(6))), 7, 8, list()) unlist(x)
package main import "fmt" func list(s ...interface{}) []interface{} { return s } func main() { s := list(list(1), 2, list(list(3, 4), 5), list(list(list())), list(list(list(6))), 7, 8, list(), ) fmt.Println(s) fmt.Println(flatten(s)) } func flatten(s []interface{}) (r []int) { for _, e := range s { switch i := e.(type) { case int: r = append(r, i) case []interface{}: r = append(r, flatten(i)...) } } return }
Write a version of this Racket function in C with identical behavior.
#lang racket (flatten '(1 (2 (3 4 5) (6 7)) 8 9))
#include <stdio.h> #include <stdlib.h> #include <string.h> typedef struct list_t list_t, *list; struct list_t{ int is_list, ival; list *lst; }; list new_list() { list x = malloc(sizeof(list_t)); x->ival = 0; x->is_list = 1; x->lst = 0; return x; } void append(list parent, list child) { parent->lst = realloc(parent->lst, sizeof(list) * (parent->ival + 1)); parent->lst[parent->ival++] = child; } list from_string(char *s, char **e, list parent) { list ret = 0; if (!parent) parent = new_list(); while (*s != '\0') { if (*s == ']') { if (e) *e = s + 1; return parent; } if (*s == '[') { ret = new_list(); ret->is_list = 1; ret->ival = 0; append(parent, ret); from_string(s + 1, &s, ret); continue; } if (*s >= '0' && *s <= '9') { ret = new_list(); ret->is_list = 0; ret->ival = strtol(s, &s, 10); append(parent, ret); continue; } s++; } if (e) *e = s; return parent; } void show_list(list l) { int i; if (!l) return; if (!l->is_list) { printf("%d", l->ival); return; } printf("["); for (i = 0; i < l->ival; i++) { show_list(l->lst[i]); if (i < l->ival - 1) printf(", "); } printf("]"); } list flatten(list from, list to) { int i; list t; if (!to) to = new_list(); if (!from->is_list) { t = new_list(); *t = *from; append(to, t); } else for (i = 0; i < from->ival; i++) flatten(from->lst[i], to); return to; } void delete_list(list l) { int i; if (!l) return; if (l->is_list && l->ival) { for (i = 0; i < l->ival; i++) delete_list(l->lst[i]); free(l->lst); } free(l); } int main() { list l = from_string("[1], 2, [[3,4], 5], [[[]]], [[[6]]], 7, 8, []", 0, 0); printf("Nested: "); show_list(l); printf("\n"); list flat = flatten(l, 0); printf("Flattened: "); show_list(flat); return 0; }
Translate this program into C but keep the logic exactly as in Racket.
#lang racket (flatten '(1 (2 (3 4 5) (6 7)) 8 9))
#include <stdio.h> #include <stdlib.h> #include <string.h> typedef struct list_t list_t, *list; struct list_t{ int is_list, ival; list *lst; }; list new_list() { list x = malloc(sizeof(list_t)); x->ival = 0; x->is_list = 1; x->lst = 0; return x; } void append(list parent, list child) { parent->lst = realloc(parent->lst, sizeof(list) * (parent->ival + 1)); parent->lst[parent->ival++] = child; } list from_string(char *s, char **e, list parent) { list ret = 0; if (!parent) parent = new_list(); while (*s != '\0') { if (*s == ']') { if (e) *e = s + 1; return parent; } if (*s == '[') { ret = new_list(); ret->is_list = 1; ret->ival = 0; append(parent, ret); from_string(s + 1, &s, ret); continue; } if (*s >= '0' && *s <= '9') { ret = new_list(); ret->is_list = 0; ret->ival = strtol(s, &s, 10); append(parent, ret); continue; } s++; } if (e) *e = s; return parent; } void show_list(list l) { int i; if (!l) return; if (!l->is_list) { printf("%d", l->ival); return; } printf("["); for (i = 0; i < l->ival; i++) { show_list(l->lst[i]); if (i < l->ival - 1) printf(", "); } printf("]"); } list flatten(list from, list to) { int i; list t; if (!to) to = new_list(); if (!from->is_list) { t = new_list(); *t = *from; append(to, t); } else for (i = 0; i < from->ival; i++) flatten(from->lst[i], to); return to; } void delete_list(list l) { int i; if (!l) return; if (l->is_list && l->ival) { for (i = 0; i < l->ival; i++) delete_list(l->lst[i]); free(l->lst); } free(l); } int main() { list l = from_string("[1], 2, [[3,4], 5], [[[]]], [[[6]]], 7, 8, []", 0, 0); printf("Nested: "); show_list(l); printf("\n"); list flat = flatten(l, 0); printf("Flattened: "); show_list(flat); return 0; }
Write the same code in C# as shown below in Racket.
#lang racket (flatten '(1 (2 (3 4 5) (6 7)) 8 9))
using System; using System.Collections; using System.Linq; namespace RosettaCodeTasks { static class FlattenList { public static ArrayList Flatten(this ArrayList List) { ArrayList NewList = new ArrayList ( ); NewList.AddRange ( List ); while ( NewList.OfType<ArrayList> ( ).Count ( ) > 0 ) { int index = NewList.IndexOf ( NewList.OfType<ArrayList> ( ).ElementAt ( 0 ) ); ArrayList Temp = (ArrayList)NewList[index]; NewList.RemoveAt ( index ); NewList.InsertRange ( index, Temp ); } return NewList; } } }
Keep all operations the same but rewrite the snippet in C#.
#lang racket (flatten '(1 (2 (3 4 5) (6 7)) 8 9))
using System; using System.Collections; using System.Linq; namespace RosettaCodeTasks { static class FlattenList { public static ArrayList Flatten(this ArrayList List) { ArrayList NewList = new ArrayList ( ); NewList.AddRange ( List ); while ( NewList.OfType<ArrayList> ( ).Count ( ) > 0 ) { int index = NewList.IndexOf ( NewList.OfType<ArrayList> ( ).ElementAt ( 0 ) ); ArrayList Temp = (ArrayList)NewList[index]; NewList.RemoveAt ( index ); NewList.InsertRange ( index, Temp ); } return NewList; } } }
Convert this Racket block to C++, preserving its control flow and logic.
#lang racket (flatten '(1 (2 (3 4 5) (6 7)) 8 9))
#include <list> #include <boost/any.hpp> typedef std::list<boost::any> anylist; void flatten(std::list<boost::any>& list) { typedef anylist::iterator iterator; iterator current = list.begin(); while (current != list.end()) { if (current->type() == typeid(anylist)) { iterator next = current; ++next; list.splice(next, boost::any_cast<anylist&>(*current)); current = list.erase(current); } else ++current; } }
Write the same code in C++ as shown below in Racket.
#lang racket (flatten '(1 (2 (3 4 5) (6 7)) 8 9))
#include <list> #include <boost/any.hpp> typedef std::list<boost::any> anylist; void flatten(std::list<boost::any>& list) { typedef anylist::iterator iterator; iterator current = list.begin(); while (current != list.end()) { if (current->type() == typeid(anylist)) { iterator next = current; ++next; list.splice(next, boost::any_cast<anylist&>(*current)); current = list.erase(current); } else ++current; } }
Rewrite this program in Java while keeping its functionality equivalent to the Racket version.
#lang racket (flatten '(1 (2 (3 4 5) (6 7)) 8 9))
import java.util.LinkedList; import java.util.List; public final class FlattenUtil { public static List<Object> flatten(List<?> list) { List<Object> retVal = new LinkedList<Object>(); flatten(list, retVal); return retVal; } public static void flatten(List<?> fromTreeList, List<Object> toFlatList) { for (Object item : fromTreeList) { if (item instanceof List<?>) { flatten((List<?>) item, toFlatList); } else { toFlatList.add(item); } } } }
Convert the following code from Racket to Java, ensuring the logic remains intact.
#lang racket (flatten '(1 (2 (3 4 5) (6 7)) 8 9))
import java.util.LinkedList; import java.util.List; public final class FlattenUtil { public static List<Object> flatten(List<?> list) { List<Object> retVal = new LinkedList<Object>(); flatten(list, retVal); return retVal; } public static void flatten(List<?> fromTreeList, List<Object> toFlatList) { for (Object item : fromTreeList) { if (item instanceof List<?>) { flatten((List<?>) item, toFlatList); } else { toFlatList.add(item); } } } }
Convert this Racket block to Python, preserving its control flow and logic.
#lang racket (flatten '(1 (2 (3 4 5) (6 7)) 8 9))
>>> def flatten(lst): return sum( ([x] if not isinstance(x, list) else flatten(x) for x in lst), [] ) >>> lst = [[1], 2, [[3,4], 5], [[[]]], [[[6]]], 7, 8, []] >>> flatten(lst) [1, 2, 3, 4, 5, 6, 7, 8]
Produce a language-to-language conversion: from Racket to Python, same semantics.
#lang racket (flatten '(1 (2 (3 4 5) (6 7)) 8 9))
>>> def flatten(lst): return sum( ([x] if not isinstance(x, list) else flatten(x) for x in lst), [] ) >>> lst = [[1], 2, [[3,4], 5], [[[]]], [[[6]]], 7, 8, []] >>> flatten(lst) [1, 2, 3, 4, 5, 6, 7, 8]
Generate a VB translation of this Racket snippet without changing its computational steps.
#lang racket (flatten '(1 (2 (3 4 5) (6 7)) 8 9))
class flattener dim separator sub class_initialize separator = "," end sub private function makeflat( a ) dim i dim res for i = lbound( a ) to ubound( a ) if isarray( a( i ) ) then res = res & makeflat( a( i ) ) else res = res & a( i ) & separator end if next makeflat = res end function public function flatten( a ) dim res res = makeflat( a ) res = left( res, len( res ) - len(separator)) res = split( res, separator ) flatten = res end function public property let itemSeparator( c ) separator = c end property end class
Convert the following code from Racket to VB, ensuring the logic remains intact.
#lang racket (flatten '(1 (2 (3 4 5) (6 7)) 8 9))
class flattener dim separator sub class_initialize separator = "," end sub private function makeflat( a ) dim i dim res for i = lbound( a ) to ubound( a ) if isarray( a( i ) ) then res = res & makeflat( a( i ) ) else res = res & a( i ) & separator end if next makeflat = res end function public function flatten( a ) dim res res = makeflat( a ) res = left( res, len( res ) - len(separator)) res = split( res, separator ) flatten = res end function public property let itemSeparator( c ) separator = c end property end class
Translate the given Racket code snippet into Go without altering its behavior.
#lang racket (flatten '(1 (2 (3 4 5) (6 7)) 8 9))
package main import "fmt" func list(s ...interface{}) []interface{} { return s } func main() { s := list(list(1), 2, list(list(3, 4), 5), list(list(list())), list(list(list(6))), 7, 8, list(), ) fmt.Println(s) fmt.Println(flatten(s)) } func flatten(s []interface{}) (r []int) { for _, e := range s { switch i := e.(type) { case int: r = append(r, i) case []interface{}: r = append(r, flatten(i)...) } } return }
Convert this Racket snippet to Go and keep its semantics consistent.
#lang racket (flatten '(1 (2 (3 4 5) (6 7)) 8 9))
package main import "fmt" func list(s ...interface{}) []interface{} { return s } func main() { s := list(list(1), 2, list(list(3, 4), 5), list(list(list())), list(list(list(6))), 7, 8, list(), ) fmt.Println(s) fmt.Println(flatten(s)) } func flatten(s []interface{}) (r []int) { for _, e := range s { switch i := e.(type) { case int: r = append(r, i) case []interface{}: r = append(r, flatten(i)...) } } return }
Produce a language-to-language conversion: from REXX to C, same semantics.
sub1 = .array~of(1) sub2 = .array~of(3, 4) sub3 = .array~of(sub2, 5) sub4 = .array~of(.array~of(.array~new)) sub5 = .array~of(.array~of(.array~of(6))) sub6 = .array~new -- final list construction list = .array~of(sub1, 2, sub3, sub4, sub5, 7, 8, sub6) -- flatten flatlist = flattenList(list) say "["flatlist~toString("line", ", ")"]" ::routine flattenList use arg list -- we could use a list or queue, but let's just use an array accumulator = .array~new -- now go to the recursive processing version call flattenSublist list, accumulator return accumulator ::routine flattenSublist use arg list, accumulator -- ask for the items explicitly, since this will allow -- us to flatten indexed collections as well do item over list~allItems -- if the object is some sort of collection, flatten this out rather -- than add to the accumulator if item~isA(.collection) then call flattenSublist item, accumulator else accumulator~append(item) end
#include <stdio.h> #include <stdlib.h> #include <string.h> typedef struct list_t list_t, *list; struct list_t{ int is_list, ival; list *lst; }; list new_list() { list x = malloc(sizeof(list_t)); x->ival = 0; x->is_list = 1; x->lst = 0; return x; } void append(list parent, list child) { parent->lst = realloc(parent->lst, sizeof(list) * (parent->ival + 1)); parent->lst[parent->ival++] = child; } list from_string(char *s, char **e, list parent) { list ret = 0; if (!parent) parent = new_list(); while (*s != '\0') { if (*s == ']') { if (e) *e = s + 1; return parent; } if (*s == '[') { ret = new_list(); ret->is_list = 1; ret->ival = 0; append(parent, ret); from_string(s + 1, &s, ret); continue; } if (*s >= '0' && *s <= '9') { ret = new_list(); ret->is_list = 0; ret->ival = strtol(s, &s, 10); append(parent, ret); continue; } s++; } if (e) *e = s; return parent; } void show_list(list l) { int i; if (!l) return; if (!l->is_list) { printf("%d", l->ival); return; } printf("["); for (i = 0; i < l->ival; i++) { show_list(l->lst[i]); if (i < l->ival - 1) printf(", "); } printf("]"); } list flatten(list from, list to) { int i; list t; if (!to) to = new_list(); if (!from->is_list) { t = new_list(); *t = *from; append(to, t); } else for (i = 0; i < from->ival; i++) flatten(from->lst[i], to); return to; } void delete_list(list l) { int i; if (!l) return; if (l->is_list && l->ival) { for (i = 0; i < l->ival; i++) delete_list(l->lst[i]); free(l->lst); } free(l); } int main() { list l = from_string("[1], 2, [[3,4], 5], [[[]]], [[[6]]], 7, 8, []", 0, 0); printf("Nested: "); show_list(l); printf("\n"); list flat = flatten(l, 0); printf("Flattened: "); show_list(flat); return 0; }
Transform the following REXX implementation into C, maintaining the same output and logic.
sub1 = .array~of(1) sub2 = .array~of(3, 4) sub3 = .array~of(sub2, 5) sub4 = .array~of(.array~of(.array~new)) sub5 = .array~of(.array~of(.array~of(6))) sub6 = .array~new -- final list construction list = .array~of(sub1, 2, sub3, sub4, sub5, 7, 8, sub6) -- flatten flatlist = flattenList(list) say "["flatlist~toString("line", ", ")"]" ::routine flattenList use arg list -- we could use a list or queue, but let's just use an array accumulator = .array~new -- now go to the recursive processing version call flattenSublist list, accumulator return accumulator ::routine flattenSublist use arg list, accumulator -- ask for the items explicitly, since this will allow -- us to flatten indexed collections as well do item over list~allItems -- if the object is some sort of collection, flatten this out rather -- than add to the accumulator if item~isA(.collection) then call flattenSublist item, accumulator else accumulator~append(item) end
#include <stdio.h> #include <stdlib.h> #include <string.h> typedef struct list_t list_t, *list; struct list_t{ int is_list, ival; list *lst; }; list new_list() { list x = malloc(sizeof(list_t)); x->ival = 0; x->is_list = 1; x->lst = 0; return x; } void append(list parent, list child) { parent->lst = realloc(parent->lst, sizeof(list) * (parent->ival + 1)); parent->lst[parent->ival++] = child; } list from_string(char *s, char **e, list parent) { list ret = 0; if (!parent) parent = new_list(); while (*s != '\0') { if (*s == ']') { if (e) *e = s + 1; return parent; } if (*s == '[') { ret = new_list(); ret->is_list = 1; ret->ival = 0; append(parent, ret); from_string(s + 1, &s, ret); continue; } if (*s >= '0' && *s <= '9') { ret = new_list(); ret->is_list = 0; ret->ival = strtol(s, &s, 10); append(parent, ret); continue; } s++; } if (e) *e = s; return parent; } void show_list(list l) { int i; if (!l) return; if (!l->is_list) { printf("%d", l->ival); return; } printf("["); for (i = 0; i < l->ival; i++) { show_list(l->lst[i]); if (i < l->ival - 1) printf(", "); } printf("]"); } list flatten(list from, list to) { int i; list t; if (!to) to = new_list(); if (!from->is_list) { t = new_list(); *t = *from; append(to, t); } else for (i = 0; i < from->ival; i++) flatten(from->lst[i], to); return to; } void delete_list(list l) { int i; if (!l) return; if (l->is_list && l->ival) { for (i = 0; i < l->ival; i++) delete_list(l->lst[i]); free(l->lst); } free(l); } int main() { list l = from_string("[1], 2, [[3,4], 5], [[[]]], [[[6]]], 7, 8, []", 0, 0); printf("Nested: "); show_list(l); printf("\n"); list flat = flatten(l, 0); printf("Flattened: "); show_list(flat); return 0; }
Rewrite the snippet below in C# so it works the same as the original REXX code.
sub1 = .array~of(1) sub2 = .array~of(3, 4) sub3 = .array~of(sub2, 5) sub4 = .array~of(.array~of(.array~new)) sub5 = .array~of(.array~of(.array~of(6))) sub6 = .array~new -- final list construction list = .array~of(sub1, 2, sub3, sub4, sub5, 7, 8, sub6) -- flatten flatlist = flattenList(list) say "["flatlist~toString("line", ", ")"]" ::routine flattenList use arg list -- we could use a list or queue, but let's just use an array accumulator = .array~new -- now go to the recursive processing version call flattenSublist list, accumulator return accumulator ::routine flattenSublist use arg list, accumulator -- ask for the items explicitly, since this will allow -- us to flatten indexed collections as well do item over list~allItems -- if the object is some sort of collection, flatten this out rather -- than add to the accumulator if item~isA(.collection) then call flattenSublist item, accumulator else accumulator~append(item) end
using System; using System.Collections; using System.Linq; namespace RosettaCodeTasks { static class FlattenList { public static ArrayList Flatten(this ArrayList List) { ArrayList NewList = new ArrayList ( ); NewList.AddRange ( List ); while ( NewList.OfType<ArrayList> ( ).Count ( ) > 0 ) { int index = NewList.IndexOf ( NewList.OfType<ArrayList> ( ).ElementAt ( 0 ) ); ArrayList Temp = (ArrayList)NewList[index]; NewList.RemoveAt ( index ); NewList.InsertRange ( index, Temp ); } return NewList; } } }
Produce a functionally identical C# code for the snippet given in REXX.
sub1 = .array~of(1) sub2 = .array~of(3, 4) sub3 = .array~of(sub2, 5) sub4 = .array~of(.array~of(.array~new)) sub5 = .array~of(.array~of(.array~of(6))) sub6 = .array~new -- final list construction list = .array~of(sub1, 2, sub3, sub4, sub5, 7, 8, sub6) -- flatten flatlist = flattenList(list) say "["flatlist~toString("line", ", ")"]" ::routine flattenList use arg list -- we could use a list or queue, but let's just use an array accumulator = .array~new -- now go to the recursive processing version call flattenSublist list, accumulator return accumulator ::routine flattenSublist use arg list, accumulator -- ask for the items explicitly, since this will allow -- us to flatten indexed collections as well do item over list~allItems -- if the object is some sort of collection, flatten this out rather -- than add to the accumulator if item~isA(.collection) then call flattenSublist item, accumulator else accumulator~append(item) end
using System; using System.Collections; using System.Linq; namespace RosettaCodeTasks { static class FlattenList { public static ArrayList Flatten(this ArrayList List) { ArrayList NewList = new ArrayList ( ); NewList.AddRange ( List ); while ( NewList.OfType<ArrayList> ( ).Count ( ) > 0 ) { int index = NewList.IndexOf ( NewList.OfType<ArrayList> ( ).ElementAt ( 0 ) ); ArrayList Temp = (ArrayList)NewList[index]; NewList.RemoveAt ( index ); NewList.InsertRange ( index, Temp ); } return NewList; } } }
Rewrite this program in C++ while keeping its functionality equivalent to the REXX version.
sub1 = .array~of(1) sub2 = .array~of(3, 4) sub3 = .array~of(sub2, 5) sub4 = .array~of(.array~of(.array~new)) sub5 = .array~of(.array~of(.array~of(6))) sub6 = .array~new -- final list construction list = .array~of(sub1, 2, sub3, sub4, sub5, 7, 8, sub6) -- flatten flatlist = flattenList(list) say "["flatlist~toString("line", ", ")"]" ::routine flattenList use arg list -- we could use a list or queue, but let's just use an array accumulator = .array~new -- now go to the recursive processing version call flattenSublist list, accumulator return accumulator ::routine flattenSublist use arg list, accumulator -- ask for the items explicitly, since this will allow -- us to flatten indexed collections as well do item over list~allItems -- if the object is some sort of collection, flatten this out rather -- than add to the accumulator if item~isA(.collection) then call flattenSublist item, accumulator else accumulator~append(item) end
#include <list> #include <boost/any.hpp> typedef std::list<boost::any> anylist; void flatten(std::list<boost::any>& list) { typedef anylist::iterator iterator; iterator current = list.begin(); while (current != list.end()) { if (current->type() == typeid(anylist)) { iterator next = current; ++next; list.splice(next, boost::any_cast<anylist&>(*current)); current = list.erase(current); } else ++current; } }
Translate this program into C++ but keep the logic exactly as in REXX.
sub1 = .array~of(1) sub2 = .array~of(3, 4) sub3 = .array~of(sub2, 5) sub4 = .array~of(.array~of(.array~new)) sub5 = .array~of(.array~of(.array~of(6))) sub6 = .array~new -- final list construction list = .array~of(sub1, 2, sub3, sub4, sub5, 7, 8, sub6) -- flatten flatlist = flattenList(list) say "["flatlist~toString("line", ", ")"]" ::routine flattenList use arg list -- we could use a list or queue, but let's just use an array accumulator = .array~new -- now go to the recursive processing version call flattenSublist list, accumulator return accumulator ::routine flattenSublist use arg list, accumulator -- ask for the items explicitly, since this will allow -- us to flatten indexed collections as well do item over list~allItems -- if the object is some sort of collection, flatten this out rather -- than add to the accumulator if item~isA(.collection) then call flattenSublist item, accumulator else accumulator~append(item) end
#include <list> #include <boost/any.hpp> typedef std::list<boost::any> anylist; void flatten(std::list<boost::any>& list) { typedef anylist::iterator iterator; iterator current = list.begin(); while (current != list.end()) { if (current->type() == typeid(anylist)) { iterator next = current; ++next; list.splice(next, boost::any_cast<anylist&>(*current)); current = list.erase(current); } else ++current; } }
Preserve the algorithm and functionality while converting the code from REXX to Java.
sub1 = .array~of(1) sub2 = .array~of(3, 4) sub3 = .array~of(sub2, 5) sub4 = .array~of(.array~of(.array~new)) sub5 = .array~of(.array~of(.array~of(6))) sub6 = .array~new -- final list construction list = .array~of(sub1, 2, sub3, sub4, sub5, 7, 8, sub6) -- flatten flatlist = flattenList(list) say "["flatlist~toString("line", ", ")"]" ::routine flattenList use arg list -- we could use a list or queue, but let's just use an array accumulator = .array~new -- now go to the recursive processing version call flattenSublist list, accumulator return accumulator ::routine flattenSublist use arg list, accumulator -- ask for the items explicitly, since this will allow -- us to flatten indexed collections as well do item over list~allItems -- if the object is some sort of collection, flatten this out rather -- than add to the accumulator if item~isA(.collection) then call flattenSublist item, accumulator else accumulator~append(item) end
import java.util.LinkedList; import java.util.List; public final class FlattenUtil { public static List<Object> flatten(List<?> list) { List<Object> retVal = new LinkedList<Object>(); flatten(list, retVal); return retVal; } public static void flatten(List<?> fromTreeList, List<Object> toFlatList) { for (Object item : fromTreeList) { if (item instanceof List<?>) { flatten((List<?>) item, toFlatList); } else { toFlatList.add(item); } } } }
Preserve the algorithm and functionality while converting the code from REXX to Java.
sub1 = .array~of(1) sub2 = .array~of(3, 4) sub3 = .array~of(sub2, 5) sub4 = .array~of(.array~of(.array~new)) sub5 = .array~of(.array~of(.array~of(6))) sub6 = .array~new -- final list construction list = .array~of(sub1, 2, sub3, sub4, sub5, 7, 8, sub6) -- flatten flatlist = flattenList(list) say "["flatlist~toString("line", ", ")"]" ::routine flattenList use arg list -- we could use a list or queue, but let's just use an array accumulator = .array~new -- now go to the recursive processing version call flattenSublist list, accumulator return accumulator ::routine flattenSublist use arg list, accumulator -- ask for the items explicitly, since this will allow -- us to flatten indexed collections as well do item over list~allItems -- if the object is some sort of collection, flatten this out rather -- than add to the accumulator if item~isA(.collection) then call flattenSublist item, accumulator else accumulator~append(item) end
import java.util.LinkedList; import java.util.List; public final class FlattenUtil { public static List<Object> flatten(List<?> list) { List<Object> retVal = new LinkedList<Object>(); flatten(list, retVal); return retVal; } public static void flatten(List<?> fromTreeList, List<Object> toFlatList) { for (Object item : fromTreeList) { if (item instanceof List<?>) { flatten((List<?>) item, toFlatList); } else { toFlatList.add(item); } } } }
Write the same algorithm in Python as shown in this REXX implementation.
sub1 = .array~of(1) sub2 = .array~of(3, 4) sub3 = .array~of(sub2, 5) sub4 = .array~of(.array~of(.array~new)) sub5 = .array~of(.array~of(.array~of(6))) sub6 = .array~new -- final list construction list = .array~of(sub1, 2, sub3, sub4, sub5, 7, 8, sub6) -- flatten flatlist = flattenList(list) say "["flatlist~toString("line", ", ")"]" ::routine flattenList use arg list -- we could use a list or queue, but let's just use an array accumulator = .array~new -- now go to the recursive processing version call flattenSublist list, accumulator return accumulator ::routine flattenSublist use arg list, accumulator -- ask for the items explicitly, since this will allow -- us to flatten indexed collections as well do item over list~allItems -- if the object is some sort of collection, flatten this out rather -- than add to the accumulator if item~isA(.collection) then call flattenSublist item, accumulator else accumulator~append(item) end
>>> def flatten(lst): return sum( ([x] if not isinstance(x, list) else flatten(x) for x in lst), [] ) >>> lst = [[1], 2, [[3,4], 5], [[[]]], [[[6]]], 7, 8, []] >>> flatten(lst) [1, 2, 3, 4, 5, 6, 7, 8]
Generate a Python translation of this REXX snippet without changing its computational steps.
sub1 = .array~of(1) sub2 = .array~of(3, 4) sub3 = .array~of(sub2, 5) sub4 = .array~of(.array~of(.array~new)) sub5 = .array~of(.array~of(.array~of(6))) sub6 = .array~new -- final list construction list = .array~of(sub1, 2, sub3, sub4, sub5, 7, 8, sub6) -- flatten flatlist = flattenList(list) say "["flatlist~toString("line", ", ")"]" ::routine flattenList use arg list -- we could use a list or queue, but let's just use an array accumulator = .array~new -- now go to the recursive processing version call flattenSublist list, accumulator return accumulator ::routine flattenSublist use arg list, accumulator -- ask for the items explicitly, since this will allow -- us to flatten indexed collections as well do item over list~allItems -- if the object is some sort of collection, flatten this out rather -- than add to the accumulator if item~isA(.collection) then call flattenSublist item, accumulator else accumulator~append(item) end
>>> def flatten(lst): return sum( ([x] if not isinstance(x, list) else flatten(x) for x in lst), [] ) >>> lst = [[1], 2, [[3,4], 5], [[[]]], [[[6]]], 7, 8, []] >>> flatten(lst) [1, 2, 3, 4, 5, 6, 7, 8]
Port the following code from REXX to VB with equivalent syntax and logic.
sub1 = .array~of(1) sub2 = .array~of(3, 4) sub3 = .array~of(sub2, 5) sub4 = .array~of(.array~of(.array~new)) sub5 = .array~of(.array~of(.array~of(6))) sub6 = .array~new -- final list construction list = .array~of(sub1, 2, sub3, sub4, sub5, 7, 8, sub6) -- flatten flatlist = flattenList(list) say "["flatlist~toString("line", ", ")"]" ::routine flattenList use arg list -- we could use a list or queue, but let's just use an array accumulator = .array~new -- now go to the recursive processing version call flattenSublist list, accumulator return accumulator ::routine flattenSublist use arg list, accumulator -- ask for the items explicitly, since this will allow -- us to flatten indexed collections as well do item over list~allItems -- if the object is some sort of collection, flatten this out rather -- than add to the accumulator if item~isA(.collection) then call flattenSublist item, accumulator else accumulator~append(item) end
class flattener dim separator sub class_initialize separator = "," end sub private function makeflat( a ) dim i dim res for i = lbound( a ) to ubound( a ) if isarray( a( i ) ) then res = res & makeflat( a( i ) ) else res = res & a( i ) & separator end if next makeflat = res end function public function flatten( a ) dim res res = makeflat( a ) res = left( res, len( res ) - len(separator)) res = split( res, separator ) flatten = res end function public property let itemSeparator( c ) separator = c end property end class
Maintain the same structure and functionality when rewriting this code in VB.
sub1 = .array~of(1) sub2 = .array~of(3, 4) sub3 = .array~of(sub2, 5) sub4 = .array~of(.array~of(.array~new)) sub5 = .array~of(.array~of(.array~of(6))) sub6 = .array~new -- final list construction list = .array~of(sub1, 2, sub3, sub4, sub5, 7, 8, sub6) -- flatten flatlist = flattenList(list) say "["flatlist~toString("line", ", ")"]" ::routine flattenList use arg list -- we could use a list or queue, but let's just use an array accumulator = .array~new -- now go to the recursive processing version call flattenSublist list, accumulator return accumulator ::routine flattenSublist use arg list, accumulator -- ask for the items explicitly, since this will allow -- us to flatten indexed collections as well do item over list~allItems -- if the object is some sort of collection, flatten this out rather -- than add to the accumulator if item~isA(.collection) then call flattenSublist item, accumulator else accumulator~append(item) end
class flattener dim separator sub class_initialize separator = "," end sub private function makeflat( a ) dim i dim res for i = lbound( a ) to ubound( a ) if isarray( a( i ) ) then res = res & makeflat( a( i ) ) else res = res & a( i ) & separator end if next makeflat = res end function public function flatten( a ) dim res res = makeflat( a ) res = left( res, len( res ) - len(separator)) res = split( res, separator ) flatten = res end function public property let itemSeparator( c ) separator = c end property end class
Port the following code from REXX to Go with equivalent syntax and logic.
sub1 = .array~of(1) sub2 = .array~of(3, 4) sub3 = .array~of(sub2, 5) sub4 = .array~of(.array~of(.array~new)) sub5 = .array~of(.array~of(.array~of(6))) sub6 = .array~new -- final list construction list = .array~of(sub1, 2, sub3, sub4, sub5, 7, 8, sub6) -- flatten flatlist = flattenList(list) say "["flatlist~toString("line", ", ")"]" ::routine flattenList use arg list -- we could use a list or queue, but let's just use an array accumulator = .array~new -- now go to the recursive processing version call flattenSublist list, accumulator return accumulator ::routine flattenSublist use arg list, accumulator -- ask for the items explicitly, since this will allow -- us to flatten indexed collections as well do item over list~allItems -- if the object is some sort of collection, flatten this out rather -- than add to the accumulator if item~isA(.collection) then call flattenSublist item, accumulator else accumulator~append(item) end
package main import "fmt" func list(s ...interface{}) []interface{} { return s } func main() { s := list(list(1), 2, list(list(3, 4), 5), list(list(list())), list(list(list(6))), 7, 8, list(), ) fmt.Println(s) fmt.Println(flatten(s)) } func flatten(s []interface{}) (r []int) { for _, e := range s { switch i := e.(type) { case int: r = append(r, i) case []interface{}: r = append(r, flatten(i)...) } } return }
Port the following code from REXX to Go with equivalent syntax and logic.
sub1 = .array~of(1) sub2 = .array~of(3, 4) sub3 = .array~of(sub2, 5) sub4 = .array~of(.array~of(.array~new)) sub5 = .array~of(.array~of(.array~of(6))) sub6 = .array~new -- final list construction list = .array~of(sub1, 2, sub3, sub4, sub5, 7, 8, sub6) -- flatten flatlist = flattenList(list) say "["flatlist~toString("line", ", ")"]" ::routine flattenList use arg list -- we could use a list or queue, but let's just use an array accumulator = .array~new -- now go to the recursive processing version call flattenSublist list, accumulator return accumulator ::routine flattenSublist use arg list, accumulator -- ask for the items explicitly, since this will allow -- us to flatten indexed collections as well do item over list~allItems -- if the object is some sort of collection, flatten this out rather -- than add to the accumulator if item~isA(.collection) then call flattenSublist item, accumulator else accumulator~append(item) end
package main import "fmt" func list(s ...interface{}) []interface{} { return s } func main() { s := list(list(1), 2, list(list(3, 4), 5), list(list(list())), list(list(list(6))), 7, 8, list(), ) fmt.Println(s) fmt.Println(flatten(s)) } func flatten(s []interface{}) (r []int) { for _, e := range s { switch i := e.(type) { case int: r = append(r, i) case []interface{}: r = append(r, flatten(i)...) } } return }
Write a version of this Ruby function in C with identical behavior.
[[1], 2, [[3, 4], 5], [[[] of Int32]], [[[6]]], 7, 8, [] of Int32].flatten()
#include <stdio.h> #include <stdlib.h> #include <string.h> typedef struct list_t list_t, *list; struct list_t{ int is_list, ival; list *lst; }; list new_list() { list x = malloc(sizeof(list_t)); x->ival = 0; x->is_list = 1; x->lst = 0; return x; } void append(list parent, list child) { parent->lst = realloc(parent->lst, sizeof(list) * (parent->ival + 1)); parent->lst[parent->ival++] = child; } list from_string(char *s, char **e, list parent) { list ret = 0; if (!parent) parent = new_list(); while (*s != '\0') { if (*s == ']') { if (e) *e = s + 1; return parent; } if (*s == '[') { ret = new_list(); ret->is_list = 1; ret->ival = 0; append(parent, ret); from_string(s + 1, &s, ret); continue; } if (*s >= '0' && *s <= '9') { ret = new_list(); ret->is_list = 0; ret->ival = strtol(s, &s, 10); append(parent, ret); continue; } s++; } if (e) *e = s; return parent; } void show_list(list l) { int i; if (!l) return; if (!l->is_list) { printf("%d", l->ival); return; } printf("["); for (i = 0; i < l->ival; i++) { show_list(l->lst[i]); if (i < l->ival - 1) printf(", "); } printf("]"); } list flatten(list from, list to) { int i; list t; if (!to) to = new_list(); if (!from->is_list) { t = new_list(); *t = *from; append(to, t); } else for (i = 0; i < from->ival; i++) flatten(from->lst[i], to); return to; } void delete_list(list l) { int i; if (!l) return; if (l->is_list && l->ival) { for (i = 0; i < l->ival; i++) delete_list(l->lst[i]); free(l->lst); } free(l); } int main() { list l = from_string("[1], 2, [[3,4], 5], [[[]]], [[[6]]], 7, 8, []", 0, 0); printf("Nested: "); show_list(l); printf("\n"); list flat = flatten(l, 0); printf("Flattened: "); show_list(flat); return 0; }
Can you help me rewrite this code in C instead of Ruby, keeping it the same logically?
[[1], 2, [[3, 4], 5], [[[] of Int32]], [[[6]]], 7, 8, [] of Int32].flatten()
#include <stdio.h> #include <stdlib.h> #include <string.h> typedef struct list_t list_t, *list; struct list_t{ int is_list, ival; list *lst; }; list new_list() { list x = malloc(sizeof(list_t)); x->ival = 0; x->is_list = 1; x->lst = 0; return x; } void append(list parent, list child) { parent->lst = realloc(parent->lst, sizeof(list) * (parent->ival + 1)); parent->lst[parent->ival++] = child; } list from_string(char *s, char **e, list parent) { list ret = 0; if (!parent) parent = new_list(); while (*s != '\0') { if (*s == ']') { if (e) *e = s + 1; return parent; } if (*s == '[') { ret = new_list(); ret->is_list = 1; ret->ival = 0; append(parent, ret); from_string(s + 1, &s, ret); continue; } if (*s >= '0' && *s <= '9') { ret = new_list(); ret->is_list = 0; ret->ival = strtol(s, &s, 10); append(parent, ret); continue; } s++; } if (e) *e = s; return parent; } void show_list(list l) { int i; if (!l) return; if (!l->is_list) { printf("%d", l->ival); return; } printf("["); for (i = 0; i < l->ival; i++) { show_list(l->lst[i]); if (i < l->ival - 1) printf(", "); } printf("]"); } list flatten(list from, list to) { int i; list t; if (!to) to = new_list(); if (!from->is_list) { t = new_list(); *t = *from; append(to, t); } else for (i = 0; i < from->ival; i++) flatten(from->lst[i], to); return to; } void delete_list(list l) { int i; if (!l) return; if (l->is_list && l->ival) { for (i = 0; i < l->ival; i++) delete_list(l->lst[i]); free(l->lst); } free(l); } int main() { list l = from_string("[1], 2, [[3,4], 5], [[[]]], [[[6]]], 7, 8, []", 0, 0); printf("Nested: "); show_list(l); printf("\n"); list flat = flatten(l, 0); printf("Flattened: "); show_list(flat); return 0; }
Write a version of this Ruby function in C# with identical behavior.
[[1], 2, [[3, 4], 5], [[[] of Int32]], [[[6]]], 7, 8, [] of Int32].flatten()
using System; using System.Collections; using System.Linq; namespace RosettaCodeTasks { static class FlattenList { public static ArrayList Flatten(this ArrayList List) { ArrayList NewList = new ArrayList ( ); NewList.AddRange ( List ); while ( NewList.OfType<ArrayList> ( ).Count ( ) > 0 ) { int index = NewList.IndexOf ( NewList.OfType<ArrayList> ( ).ElementAt ( 0 ) ); ArrayList Temp = (ArrayList)NewList[index]; NewList.RemoveAt ( index ); NewList.InsertRange ( index, Temp ); } return NewList; } } }
Port the following code from Ruby to C# with equivalent syntax and logic.
[[1], 2, [[3, 4], 5], [[[] of Int32]], [[[6]]], 7, 8, [] of Int32].flatten()
using System; using System.Collections; using System.Linq; namespace RosettaCodeTasks { static class FlattenList { public static ArrayList Flatten(this ArrayList List) { ArrayList NewList = new ArrayList ( ); NewList.AddRange ( List ); while ( NewList.OfType<ArrayList> ( ).Count ( ) > 0 ) { int index = NewList.IndexOf ( NewList.OfType<ArrayList> ( ).ElementAt ( 0 ) ); ArrayList Temp = (ArrayList)NewList[index]; NewList.RemoveAt ( index ); NewList.InsertRange ( index, Temp ); } return NewList; } } }
Produce a functionally identical C++ code for the snippet given in Ruby.
[[1], 2, [[3, 4], 5], [[[] of Int32]], [[[6]]], 7, 8, [] of Int32].flatten()
#include <list> #include <boost/any.hpp> typedef std::list<boost::any> anylist; void flatten(std::list<boost::any>& list) { typedef anylist::iterator iterator; iterator current = list.begin(); while (current != list.end()) { if (current->type() == typeid(anylist)) { iterator next = current; ++next; list.splice(next, boost::any_cast<anylist&>(*current)); current = list.erase(current); } else ++current; } }
Change the following Ruby code into C++ without altering its purpose.
[[1], 2, [[3, 4], 5], [[[] of Int32]], [[[6]]], 7, 8, [] of Int32].flatten()
#include <list> #include <boost/any.hpp> typedef std::list<boost::any> anylist; void flatten(std::list<boost::any>& list) { typedef anylist::iterator iterator; iterator current = list.begin(); while (current != list.end()) { if (current->type() == typeid(anylist)) { iterator next = current; ++next; list.splice(next, boost::any_cast<anylist&>(*current)); current = list.erase(current); } else ++current; } }
Produce a functionally identical Java code for the snippet given in Ruby.
[[1], 2, [[3, 4], 5], [[[] of Int32]], [[[6]]], 7, 8, [] of Int32].flatten()
import java.util.LinkedList; import java.util.List; public final class FlattenUtil { public static List<Object> flatten(List<?> list) { List<Object> retVal = new LinkedList<Object>(); flatten(list, retVal); return retVal; } public static void flatten(List<?> fromTreeList, List<Object> toFlatList) { for (Object item : fromTreeList) { if (item instanceof List<?>) { flatten((List<?>) item, toFlatList); } else { toFlatList.add(item); } } } }
Change the programming language of this snippet from Ruby to Java without modifying what it does.
[[1], 2, [[3, 4], 5], [[[] of Int32]], [[[6]]], 7, 8, [] of Int32].flatten()
import java.util.LinkedList; import java.util.List; public final class FlattenUtil { public static List<Object> flatten(List<?> list) { List<Object> retVal = new LinkedList<Object>(); flatten(list, retVal); return retVal; } public static void flatten(List<?> fromTreeList, List<Object> toFlatList) { for (Object item : fromTreeList) { if (item instanceof List<?>) { flatten((List<?>) item, toFlatList); } else { toFlatList.add(item); } } } }
Generate a Python translation of this Ruby snippet without changing its computational steps.
[[1], 2, [[3, 4], 5], [[[] of Int32]], [[[6]]], 7, 8, [] of Int32].flatten()
>>> def flatten(lst): return sum( ([x] if not isinstance(x, list) else flatten(x) for x in lst), [] ) >>> lst = [[1], 2, [[3,4], 5], [[[]]], [[[6]]], 7, 8, []] >>> flatten(lst) [1, 2, 3, 4, 5, 6, 7, 8]
Can you help me rewrite this code in Python instead of Ruby, keeping it the same logically?
[[1], 2, [[3, 4], 5], [[[] of Int32]], [[[6]]], 7, 8, [] of Int32].flatten()
>>> def flatten(lst): return sum( ([x] if not isinstance(x, list) else flatten(x) for x in lst), [] ) >>> lst = [[1], 2, [[3,4], 5], [[[]]], [[[6]]], 7, 8, []] >>> flatten(lst) [1, 2, 3, 4, 5, 6, 7, 8]
Generate a VB translation of this Ruby snippet without changing its computational steps.
[[1], 2, [[3, 4], 5], [[[] of Int32]], [[[6]]], 7, 8, [] of Int32].flatten()
class flattener dim separator sub class_initialize separator = "," end sub private function makeflat( a ) dim i dim res for i = lbound( a ) to ubound( a ) if isarray( a( i ) ) then res = res & makeflat( a( i ) ) else res = res & a( i ) & separator end if next makeflat = res end function public function flatten( a ) dim res res = makeflat( a ) res = left( res, len( res ) - len(separator)) res = split( res, separator ) flatten = res end function public property let itemSeparator( c ) separator = c end property end class
Generate an equivalent VB version of this Ruby code.
[[1], 2, [[3, 4], 5], [[[] of Int32]], [[[6]]], 7, 8, [] of Int32].flatten()
class flattener dim separator sub class_initialize separator = "," end sub private function makeflat( a ) dim i dim res for i = lbound( a ) to ubound( a ) if isarray( a( i ) ) then res = res & makeflat( a( i ) ) else res = res & a( i ) & separator end if next makeflat = res end function public function flatten( a ) dim res res = makeflat( a ) res = left( res, len( res ) - len(separator)) res = split( res, separator ) flatten = res end function public property let itemSeparator( c ) separator = c end property end class
Rewrite the snippet below in Go so it works the same as the original Ruby code.
[[1], 2, [[3, 4], 5], [[[] of Int32]], [[[6]]], 7, 8, [] of Int32].flatten()
package main import "fmt" func list(s ...interface{}) []interface{} { return s } func main() { s := list(list(1), 2, list(list(3, 4), 5), list(list(list())), list(list(list(6))), 7, 8, list(), ) fmt.Println(s) fmt.Println(flatten(s)) } func flatten(s []interface{}) (r []int) { for _, e := range s { switch i := e.(type) { case int: r = append(r, i) case []interface{}: r = append(r, flatten(i)...) } } return }
Convert this Ruby snippet to Go and keep its semantics consistent.
[[1], 2, [[3, 4], 5], [[[] of Int32]], [[[6]]], 7, 8, [] of Int32].flatten()
package main import "fmt" func list(s ...interface{}) []interface{} { return s } func main() { s := list(list(1), 2, list(list(3, 4), 5), list(list(list())), list(list(list(6))), 7, 8, list(), ) fmt.Println(s) fmt.Println(flatten(s)) } func flatten(s []interface{}) (r []int) { for _, e := range s { switch i := e.(type) { case int: r = append(r, i) case []interface{}: r = append(r, flatten(i)...) } } return }
Rewrite the snippet below in C so it works the same as the original Scala code.
@Suppress("UNCHECKED_CAST") fun flattenList(nestList: List<Any>, flatList: MutableList<Int>) { for (e in nestList) if (e is Int) flatList.add(e) else flattenList(e as List<Any>, flatList) } fun main(args: Array<String>) { val nestList : List<Any> = listOf( listOf(1), 2, listOf(listOf(3, 4), 5), listOf(listOf(listOf<Int>())), listOf(listOf(listOf(6))), 7, 8, listOf<Int>() ) println("Nested  : " + nestList) val flatList = mutableListOf<Int>() flattenList(nestList, flatList) println("Flattened : " + flatList) }
#include <stdio.h> #include <stdlib.h> #include <string.h> typedef struct list_t list_t, *list; struct list_t{ int is_list, ival; list *lst; }; list new_list() { list x = malloc(sizeof(list_t)); x->ival = 0; x->is_list = 1; x->lst = 0; return x; } void append(list parent, list child) { parent->lst = realloc(parent->lst, sizeof(list) * (parent->ival + 1)); parent->lst[parent->ival++] = child; } list from_string(char *s, char **e, list parent) { list ret = 0; if (!parent) parent = new_list(); while (*s != '\0') { if (*s == ']') { if (e) *e = s + 1; return parent; } if (*s == '[') { ret = new_list(); ret->is_list = 1; ret->ival = 0; append(parent, ret); from_string(s + 1, &s, ret); continue; } if (*s >= '0' && *s <= '9') { ret = new_list(); ret->is_list = 0; ret->ival = strtol(s, &s, 10); append(parent, ret); continue; } s++; } if (e) *e = s; return parent; } void show_list(list l) { int i; if (!l) return; if (!l->is_list) { printf("%d", l->ival); return; } printf("["); for (i = 0; i < l->ival; i++) { show_list(l->lst[i]); if (i < l->ival - 1) printf(", "); } printf("]"); } list flatten(list from, list to) { int i; list t; if (!to) to = new_list(); if (!from->is_list) { t = new_list(); *t = *from; append(to, t); } else for (i = 0; i < from->ival; i++) flatten(from->lst[i], to); return to; } void delete_list(list l) { int i; if (!l) return; if (l->is_list && l->ival) { for (i = 0; i < l->ival; i++) delete_list(l->lst[i]); free(l->lst); } free(l); } int main() { list l = from_string("[1], 2, [[3,4], 5], [[[]]], [[[6]]], 7, 8, []", 0, 0); printf("Nested: "); show_list(l); printf("\n"); list flat = flatten(l, 0); printf("Flattened: "); show_list(flat); return 0; }
Write the same algorithm in C as shown in this Scala implementation.
@Suppress("UNCHECKED_CAST") fun flattenList(nestList: List<Any>, flatList: MutableList<Int>) { for (e in nestList) if (e is Int) flatList.add(e) else flattenList(e as List<Any>, flatList) } fun main(args: Array<String>) { val nestList : List<Any> = listOf( listOf(1), 2, listOf(listOf(3, 4), 5), listOf(listOf(listOf<Int>())), listOf(listOf(listOf(6))), 7, 8, listOf<Int>() ) println("Nested  : " + nestList) val flatList = mutableListOf<Int>() flattenList(nestList, flatList) println("Flattened : " + flatList) }
#include <stdio.h> #include <stdlib.h> #include <string.h> typedef struct list_t list_t, *list; struct list_t{ int is_list, ival; list *lst; }; list new_list() { list x = malloc(sizeof(list_t)); x->ival = 0; x->is_list = 1; x->lst = 0; return x; } void append(list parent, list child) { parent->lst = realloc(parent->lst, sizeof(list) * (parent->ival + 1)); parent->lst[parent->ival++] = child; } list from_string(char *s, char **e, list parent) { list ret = 0; if (!parent) parent = new_list(); while (*s != '\0') { if (*s == ']') { if (e) *e = s + 1; return parent; } if (*s == '[') { ret = new_list(); ret->is_list = 1; ret->ival = 0; append(parent, ret); from_string(s + 1, &s, ret); continue; } if (*s >= '0' && *s <= '9') { ret = new_list(); ret->is_list = 0; ret->ival = strtol(s, &s, 10); append(parent, ret); continue; } s++; } if (e) *e = s; return parent; } void show_list(list l) { int i; if (!l) return; if (!l->is_list) { printf("%d", l->ival); return; } printf("["); for (i = 0; i < l->ival; i++) { show_list(l->lst[i]); if (i < l->ival - 1) printf(", "); } printf("]"); } list flatten(list from, list to) { int i; list t; if (!to) to = new_list(); if (!from->is_list) { t = new_list(); *t = *from; append(to, t); } else for (i = 0; i < from->ival; i++) flatten(from->lst[i], to); return to; } void delete_list(list l) { int i; if (!l) return; if (l->is_list && l->ival) { for (i = 0; i < l->ival; i++) delete_list(l->lst[i]); free(l->lst); } free(l); } int main() { list l = from_string("[1], 2, [[3,4], 5], [[[]]], [[[6]]], 7, 8, []", 0, 0); printf("Nested: "); show_list(l); printf("\n"); list flat = flatten(l, 0); printf("Flattened: "); show_list(flat); return 0; }
Write the same code in C# as shown below in Scala.
@Suppress("UNCHECKED_CAST") fun flattenList(nestList: List<Any>, flatList: MutableList<Int>) { for (e in nestList) if (e is Int) flatList.add(e) else flattenList(e as List<Any>, flatList) } fun main(args: Array<String>) { val nestList : List<Any> = listOf( listOf(1), 2, listOf(listOf(3, 4), 5), listOf(listOf(listOf<Int>())), listOf(listOf(listOf(6))), 7, 8, listOf<Int>() ) println("Nested  : " + nestList) val flatList = mutableListOf<Int>() flattenList(nestList, flatList) println("Flattened : " + flatList) }
using System; using System.Collections; using System.Linq; namespace RosettaCodeTasks { static class FlattenList { public static ArrayList Flatten(this ArrayList List) { ArrayList NewList = new ArrayList ( ); NewList.AddRange ( List ); while ( NewList.OfType<ArrayList> ( ).Count ( ) > 0 ) { int index = NewList.IndexOf ( NewList.OfType<ArrayList> ( ).ElementAt ( 0 ) ); ArrayList Temp = (ArrayList)NewList[index]; NewList.RemoveAt ( index ); NewList.InsertRange ( index, Temp ); } return NewList; } } }
Port the provided Scala code into C# while preserving the original functionality.
@Suppress("UNCHECKED_CAST") fun flattenList(nestList: List<Any>, flatList: MutableList<Int>) { for (e in nestList) if (e is Int) flatList.add(e) else flattenList(e as List<Any>, flatList) } fun main(args: Array<String>) { val nestList : List<Any> = listOf( listOf(1), 2, listOf(listOf(3, 4), 5), listOf(listOf(listOf<Int>())), listOf(listOf(listOf(6))), 7, 8, listOf<Int>() ) println("Nested  : " + nestList) val flatList = mutableListOf<Int>() flattenList(nestList, flatList) println("Flattened : " + flatList) }
using System; using System.Collections; using System.Linq; namespace RosettaCodeTasks { static class FlattenList { public static ArrayList Flatten(this ArrayList List) { ArrayList NewList = new ArrayList ( ); NewList.AddRange ( List ); while ( NewList.OfType<ArrayList> ( ).Count ( ) > 0 ) { int index = NewList.IndexOf ( NewList.OfType<ArrayList> ( ).ElementAt ( 0 ) ); ArrayList Temp = (ArrayList)NewList[index]; NewList.RemoveAt ( index ); NewList.InsertRange ( index, Temp ); } return NewList; } } }
Produce a language-to-language conversion: from Scala to C++, same semantics.
@Suppress("UNCHECKED_CAST") fun flattenList(nestList: List<Any>, flatList: MutableList<Int>) { for (e in nestList) if (e is Int) flatList.add(e) else flattenList(e as List<Any>, flatList) } fun main(args: Array<String>) { val nestList : List<Any> = listOf( listOf(1), 2, listOf(listOf(3, 4), 5), listOf(listOf(listOf<Int>())), listOf(listOf(listOf(6))), 7, 8, listOf<Int>() ) println("Nested  : " + nestList) val flatList = mutableListOf<Int>() flattenList(nestList, flatList) println("Flattened : " + flatList) }
#include <list> #include <boost/any.hpp> typedef std::list<boost::any> anylist; void flatten(std::list<boost::any>& list) { typedef anylist::iterator iterator; iterator current = list.begin(); while (current != list.end()) { if (current->type() == typeid(anylist)) { iterator next = current; ++next; list.splice(next, boost::any_cast<anylist&>(*current)); current = list.erase(current); } else ++current; } }
Maintain the same structure and functionality when rewriting this code in C++.
@Suppress("UNCHECKED_CAST") fun flattenList(nestList: List<Any>, flatList: MutableList<Int>) { for (e in nestList) if (e is Int) flatList.add(e) else flattenList(e as List<Any>, flatList) } fun main(args: Array<String>) { val nestList : List<Any> = listOf( listOf(1), 2, listOf(listOf(3, 4), 5), listOf(listOf(listOf<Int>())), listOf(listOf(listOf(6))), 7, 8, listOf<Int>() ) println("Nested  : " + nestList) val flatList = mutableListOf<Int>() flattenList(nestList, flatList) println("Flattened : " + flatList) }
#include <list> #include <boost/any.hpp> typedef std::list<boost::any> anylist; void flatten(std::list<boost::any>& list) { typedef anylist::iterator iterator; iterator current = list.begin(); while (current != list.end()) { if (current->type() == typeid(anylist)) { iterator next = current; ++next; list.splice(next, boost::any_cast<anylist&>(*current)); current = list.erase(current); } else ++current; } }
Maintain the same structure and functionality when rewriting this code in Java.
@Suppress("UNCHECKED_CAST") fun flattenList(nestList: List<Any>, flatList: MutableList<Int>) { for (e in nestList) if (e is Int) flatList.add(e) else flattenList(e as List<Any>, flatList) } fun main(args: Array<String>) { val nestList : List<Any> = listOf( listOf(1), 2, listOf(listOf(3, 4), 5), listOf(listOf(listOf<Int>())), listOf(listOf(listOf(6))), 7, 8, listOf<Int>() ) println("Nested  : " + nestList) val flatList = mutableListOf<Int>() flattenList(nestList, flatList) println("Flattened : " + flatList) }
import java.util.LinkedList; import java.util.List; public final class FlattenUtil { public static List<Object> flatten(List<?> list) { List<Object> retVal = new LinkedList<Object>(); flatten(list, retVal); return retVal; } public static void flatten(List<?> fromTreeList, List<Object> toFlatList) { for (Object item : fromTreeList) { if (item instanceof List<?>) { flatten((List<?>) item, toFlatList); } else { toFlatList.add(item); } } } }
Change the programming language of this snippet from Scala to Java without modifying what it does.
@Suppress("UNCHECKED_CAST") fun flattenList(nestList: List<Any>, flatList: MutableList<Int>) { for (e in nestList) if (e is Int) flatList.add(e) else flattenList(e as List<Any>, flatList) } fun main(args: Array<String>) { val nestList : List<Any> = listOf( listOf(1), 2, listOf(listOf(3, 4), 5), listOf(listOf(listOf<Int>())), listOf(listOf(listOf(6))), 7, 8, listOf<Int>() ) println("Nested  : " + nestList) val flatList = mutableListOf<Int>() flattenList(nestList, flatList) println("Flattened : " + flatList) }
import java.util.LinkedList; import java.util.List; public final class FlattenUtil { public static List<Object> flatten(List<?> list) { List<Object> retVal = new LinkedList<Object>(); flatten(list, retVal); return retVal; } public static void flatten(List<?> fromTreeList, List<Object> toFlatList) { for (Object item : fromTreeList) { if (item instanceof List<?>) { flatten((List<?>) item, toFlatList); } else { toFlatList.add(item); } } } }
Translate the given Scala code snippet into Python without altering its behavior.
@Suppress("UNCHECKED_CAST") fun flattenList(nestList: List<Any>, flatList: MutableList<Int>) { for (e in nestList) if (e is Int) flatList.add(e) else flattenList(e as List<Any>, flatList) } fun main(args: Array<String>) { val nestList : List<Any> = listOf( listOf(1), 2, listOf(listOf(3, 4), 5), listOf(listOf(listOf<Int>())), listOf(listOf(listOf(6))), 7, 8, listOf<Int>() ) println("Nested  : " + nestList) val flatList = mutableListOf<Int>() flattenList(nestList, flatList) println("Flattened : " + flatList) }
>>> def flatten(lst): return sum( ([x] if not isinstance(x, list) else flatten(x) for x in lst), [] ) >>> lst = [[1], 2, [[3,4], 5], [[[]]], [[[6]]], 7, 8, []] >>> flatten(lst) [1, 2, 3, 4, 5, 6, 7, 8]
Maintain the same structure and functionality when rewriting this code in Python.
@Suppress("UNCHECKED_CAST") fun flattenList(nestList: List<Any>, flatList: MutableList<Int>) { for (e in nestList) if (e is Int) flatList.add(e) else flattenList(e as List<Any>, flatList) } fun main(args: Array<String>) { val nestList : List<Any> = listOf( listOf(1), 2, listOf(listOf(3, 4), 5), listOf(listOf(listOf<Int>())), listOf(listOf(listOf(6))), 7, 8, listOf<Int>() ) println("Nested  : " + nestList) val flatList = mutableListOf<Int>() flattenList(nestList, flatList) println("Flattened : " + flatList) }
>>> def flatten(lst): return sum( ([x] if not isinstance(x, list) else flatten(x) for x in lst), [] ) >>> lst = [[1], 2, [[3,4], 5], [[[]]], [[[6]]], 7, 8, []] >>> flatten(lst) [1, 2, 3, 4, 5, 6, 7, 8]
Convert the following code from Scala to VB, ensuring the logic remains intact.
@Suppress("UNCHECKED_CAST") fun flattenList(nestList: List<Any>, flatList: MutableList<Int>) { for (e in nestList) if (e is Int) flatList.add(e) else flattenList(e as List<Any>, flatList) } fun main(args: Array<String>) { val nestList : List<Any> = listOf( listOf(1), 2, listOf(listOf(3, 4), 5), listOf(listOf(listOf<Int>())), listOf(listOf(listOf(6))), 7, 8, listOf<Int>() ) println("Nested  : " + nestList) val flatList = mutableListOf<Int>() flattenList(nestList, flatList) println("Flattened : " + flatList) }
class flattener dim separator sub class_initialize separator = "," end sub private function makeflat( a ) dim i dim res for i = lbound( a ) to ubound( a ) if isarray( a( i ) ) then res = res & makeflat( a( i ) ) else res = res & a( i ) & separator end if next makeflat = res end function public function flatten( a ) dim res res = makeflat( a ) res = left( res, len( res ) - len(separator)) res = split( res, separator ) flatten = res end function public property let itemSeparator( c ) separator = c end property end class
Transform the following Scala implementation into VB, maintaining the same output and logic.
@Suppress("UNCHECKED_CAST") fun flattenList(nestList: List<Any>, flatList: MutableList<Int>) { for (e in nestList) if (e is Int) flatList.add(e) else flattenList(e as List<Any>, flatList) } fun main(args: Array<String>) { val nestList : List<Any> = listOf( listOf(1), 2, listOf(listOf(3, 4), 5), listOf(listOf(listOf<Int>())), listOf(listOf(listOf(6))), 7, 8, listOf<Int>() ) println("Nested  : " + nestList) val flatList = mutableListOf<Int>() flattenList(nestList, flatList) println("Flattened : " + flatList) }
class flattener dim separator sub class_initialize separator = "," end sub private function makeflat( a ) dim i dim res for i = lbound( a ) to ubound( a ) if isarray( a( i ) ) then res = res & makeflat( a( i ) ) else res = res & a( i ) & separator end if next makeflat = res end function public function flatten( a ) dim res res = makeflat( a ) res = left( res, len( res ) - len(separator)) res = split( res, separator ) flatten = res end function public property let itemSeparator( c ) separator = c end property end class
Change the following Scala code into Go without altering its purpose.
@Suppress("UNCHECKED_CAST") fun flattenList(nestList: List<Any>, flatList: MutableList<Int>) { for (e in nestList) if (e is Int) flatList.add(e) else flattenList(e as List<Any>, flatList) } fun main(args: Array<String>) { val nestList : List<Any> = listOf( listOf(1), 2, listOf(listOf(3, 4), 5), listOf(listOf(listOf<Int>())), listOf(listOf(listOf(6))), 7, 8, listOf<Int>() ) println("Nested  : " + nestList) val flatList = mutableListOf<Int>() flattenList(nestList, flatList) println("Flattened : " + flatList) }
package main import "fmt" func list(s ...interface{}) []interface{} { return s } func main() { s := list(list(1), 2, list(list(3, 4), 5), list(list(list())), list(list(list(6))), 7, 8, list(), ) fmt.Println(s) fmt.Println(flatten(s)) } func flatten(s []interface{}) (r []int) { for _, e := range s { switch i := e.(type) { case int: r = append(r, i) case []interface{}: r = append(r, flatten(i)...) } } return }
Can you help me rewrite this code in Go instead of Scala, keeping it the same logically?
@Suppress("UNCHECKED_CAST") fun flattenList(nestList: List<Any>, flatList: MutableList<Int>) { for (e in nestList) if (e is Int) flatList.add(e) else flattenList(e as List<Any>, flatList) } fun main(args: Array<String>) { val nestList : List<Any> = listOf( listOf(1), 2, listOf(listOf(3, 4), 5), listOf(listOf(listOf<Int>())), listOf(listOf(listOf(6))), 7, 8, listOf<Int>() ) println("Nested  : " + nestList) val flatList = mutableListOf<Int>() flattenList(nestList, flatList) println("Flattened : " + flatList) }
package main import "fmt" func list(s ...interface{}) []interface{} { return s } func main() { s := list(list(1), 2, list(list(3, 4), 5), list(list(list())), list(list(list(6))), 7, 8, list(), ) fmt.Println(s) fmt.Println(flatten(s)) } func flatten(s []interface{}) (r []int) { for _, e := range s { switch i := e.(type) { case int: r = append(r, i) case []interface{}: r = append(r, flatten(i)...) } } return }
Transform the following Swift implementation into C, maintaining the same output and logic.
func list(s: Any...) -> [Any] { return s } func flatten<T>(s: [Any]) -> [T] { var r = [T]() for e in s { switch e { case let a as [Any]: r += flatten(a) case let x as T: r.append(x) default: assert(false, "value of wrong type") } } return r } let s = list(list(1), 2, list(list(3, 4), 5), list(list(list())), list(list(list(6))), 7, 8, list() ) println(s) let result : [Int] = flatten(s) println(result)
#include <stdio.h> #include <stdlib.h> #include <string.h> typedef struct list_t list_t, *list; struct list_t{ int is_list, ival; list *lst; }; list new_list() { list x = malloc(sizeof(list_t)); x->ival = 0; x->is_list = 1; x->lst = 0; return x; } void append(list parent, list child) { parent->lst = realloc(parent->lst, sizeof(list) * (parent->ival + 1)); parent->lst[parent->ival++] = child; } list from_string(char *s, char **e, list parent) { list ret = 0; if (!parent) parent = new_list(); while (*s != '\0') { if (*s == ']') { if (e) *e = s + 1; return parent; } if (*s == '[') { ret = new_list(); ret->is_list = 1; ret->ival = 0; append(parent, ret); from_string(s + 1, &s, ret); continue; } if (*s >= '0' && *s <= '9') { ret = new_list(); ret->is_list = 0; ret->ival = strtol(s, &s, 10); append(parent, ret); continue; } s++; } if (e) *e = s; return parent; } void show_list(list l) { int i; if (!l) return; if (!l->is_list) { printf("%d", l->ival); return; } printf("["); for (i = 0; i < l->ival; i++) { show_list(l->lst[i]); if (i < l->ival - 1) printf(", "); } printf("]"); } list flatten(list from, list to) { int i; list t; if (!to) to = new_list(); if (!from->is_list) { t = new_list(); *t = *from; append(to, t); } else for (i = 0; i < from->ival; i++) flatten(from->lst[i], to); return to; } void delete_list(list l) { int i; if (!l) return; if (l->is_list && l->ival) { for (i = 0; i < l->ival; i++) delete_list(l->lst[i]); free(l->lst); } free(l); } int main() { list l = from_string("[1], 2, [[3,4], 5], [[[]]], [[[6]]], 7, 8, []", 0, 0); printf("Nested: "); show_list(l); printf("\n"); list flat = flatten(l, 0); printf("Flattened: "); show_list(flat); return 0; }
Translate the given Swift code snippet into C without altering its behavior.
func list(s: Any...) -> [Any] { return s } func flatten<T>(s: [Any]) -> [T] { var r = [T]() for e in s { switch e { case let a as [Any]: r += flatten(a) case let x as T: r.append(x) default: assert(false, "value of wrong type") } } return r } let s = list(list(1), 2, list(list(3, 4), 5), list(list(list())), list(list(list(6))), 7, 8, list() ) println(s) let result : [Int] = flatten(s) println(result)
#include <stdio.h> #include <stdlib.h> #include <string.h> typedef struct list_t list_t, *list; struct list_t{ int is_list, ival; list *lst; }; list new_list() { list x = malloc(sizeof(list_t)); x->ival = 0; x->is_list = 1; x->lst = 0; return x; } void append(list parent, list child) { parent->lst = realloc(parent->lst, sizeof(list) * (parent->ival + 1)); parent->lst[parent->ival++] = child; } list from_string(char *s, char **e, list parent) { list ret = 0; if (!parent) parent = new_list(); while (*s != '\0') { if (*s == ']') { if (e) *e = s + 1; return parent; } if (*s == '[') { ret = new_list(); ret->is_list = 1; ret->ival = 0; append(parent, ret); from_string(s + 1, &s, ret); continue; } if (*s >= '0' && *s <= '9') { ret = new_list(); ret->is_list = 0; ret->ival = strtol(s, &s, 10); append(parent, ret); continue; } s++; } if (e) *e = s; return parent; } void show_list(list l) { int i; if (!l) return; if (!l->is_list) { printf("%d", l->ival); return; } printf("["); for (i = 0; i < l->ival; i++) { show_list(l->lst[i]); if (i < l->ival - 1) printf(", "); } printf("]"); } list flatten(list from, list to) { int i; list t; if (!to) to = new_list(); if (!from->is_list) { t = new_list(); *t = *from; append(to, t); } else for (i = 0; i < from->ival; i++) flatten(from->lst[i], to); return to; } void delete_list(list l) { int i; if (!l) return; if (l->is_list && l->ival) { for (i = 0; i < l->ival; i++) delete_list(l->lst[i]); free(l->lst); } free(l); } int main() { list l = from_string("[1], 2, [[3,4], 5], [[[]]], [[[6]]], 7, 8, []", 0, 0); printf("Nested: "); show_list(l); printf("\n"); list flat = flatten(l, 0); printf("Flattened: "); show_list(flat); return 0; }
Rewrite this program in C# while keeping its functionality equivalent to the Swift version.
func list(s: Any...) -> [Any] { return s } func flatten<T>(s: [Any]) -> [T] { var r = [T]() for e in s { switch e { case let a as [Any]: r += flatten(a) case let x as T: r.append(x) default: assert(false, "value of wrong type") } } return r } let s = list(list(1), 2, list(list(3, 4), 5), list(list(list())), list(list(list(6))), 7, 8, list() ) println(s) let result : [Int] = flatten(s) println(result)
using System; using System.Collections; using System.Linq; namespace RosettaCodeTasks { static class FlattenList { public static ArrayList Flatten(this ArrayList List) { ArrayList NewList = new ArrayList ( ); NewList.AddRange ( List ); while ( NewList.OfType<ArrayList> ( ).Count ( ) > 0 ) { int index = NewList.IndexOf ( NewList.OfType<ArrayList> ( ).ElementAt ( 0 ) ); ArrayList Temp = (ArrayList)NewList[index]; NewList.RemoveAt ( index ); NewList.InsertRange ( index, Temp ); } return NewList; } } }
Rewrite the snippet below in C# so it works the same as the original Swift code.
func list(s: Any...) -> [Any] { return s } func flatten<T>(s: [Any]) -> [T] { var r = [T]() for e in s { switch e { case let a as [Any]: r += flatten(a) case let x as T: r.append(x) default: assert(false, "value of wrong type") } } return r } let s = list(list(1), 2, list(list(3, 4), 5), list(list(list())), list(list(list(6))), 7, 8, list() ) println(s) let result : [Int] = flatten(s) println(result)
using System; using System.Collections; using System.Linq; namespace RosettaCodeTasks { static class FlattenList { public static ArrayList Flatten(this ArrayList List) { ArrayList NewList = new ArrayList ( ); NewList.AddRange ( List ); while ( NewList.OfType<ArrayList> ( ).Count ( ) > 0 ) { int index = NewList.IndexOf ( NewList.OfType<ArrayList> ( ).ElementAt ( 0 ) ); ArrayList Temp = (ArrayList)NewList[index]; NewList.RemoveAt ( index ); NewList.InsertRange ( index, Temp ); } return NewList; } } }
Produce a functionally identical C++ code for the snippet given in Swift.
func list(s: Any...) -> [Any] { return s } func flatten<T>(s: [Any]) -> [T] { var r = [T]() for e in s { switch e { case let a as [Any]: r += flatten(a) case let x as T: r.append(x) default: assert(false, "value of wrong type") } } return r } let s = list(list(1), 2, list(list(3, 4), 5), list(list(list())), list(list(list(6))), 7, 8, list() ) println(s) let result : [Int] = flatten(s) println(result)
#include <list> #include <boost/any.hpp> typedef std::list<boost::any> anylist; void flatten(std::list<boost::any>& list) { typedef anylist::iterator iterator; iterator current = list.begin(); while (current != list.end()) { if (current->type() == typeid(anylist)) { iterator next = current; ++next; list.splice(next, boost::any_cast<anylist&>(*current)); current = list.erase(current); } else ++current; } }
Write the same code in C++ as shown below in Swift.
func list(s: Any...) -> [Any] { return s } func flatten<T>(s: [Any]) -> [T] { var r = [T]() for e in s { switch e { case let a as [Any]: r += flatten(a) case let x as T: r.append(x) default: assert(false, "value of wrong type") } } return r } let s = list(list(1), 2, list(list(3, 4), 5), list(list(list())), list(list(list(6))), 7, 8, list() ) println(s) let result : [Int] = flatten(s) println(result)
#include <list> #include <boost/any.hpp> typedef std::list<boost::any> anylist; void flatten(std::list<boost::any>& list) { typedef anylist::iterator iterator; iterator current = list.begin(); while (current != list.end()) { if (current->type() == typeid(anylist)) { iterator next = current; ++next; list.splice(next, boost::any_cast<anylist&>(*current)); current = list.erase(current); } else ++current; } }
Translate this program into Java but keep the logic exactly as in Swift.
func list(s: Any...) -> [Any] { return s } func flatten<T>(s: [Any]) -> [T] { var r = [T]() for e in s { switch e { case let a as [Any]: r += flatten(a) case let x as T: r.append(x) default: assert(false, "value of wrong type") } } return r } let s = list(list(1), 2, list(list(3, 4), 5), list(list(list())), list(list(list(6))), 7, 8, list() ) println(s) let result : [Int] = flatten(s) println(result)
import java.util.LinkedList; import java.util.List; public final class FlattenUtil { public static List<Object> flatten(List<?> list) { List<Object> retVal = new LinkedList<Object>(); flatten(list, retVal); return retVal; } public static void flatten(List<?> fromTreeList, List<Object> toFlatList) { for (Object item : fromTreeList) { if (item instanceof List<?>) { flatten((List<?>) item, toFlatList); } else { toFlatList.add(item); } } } }
Rewrite the snippet below in Java so it works the same as the original Swift code.
func list(s: Any...) -> [Any] { return s } func flatten<T>(s: [Any]) -> [T] { var r = [T]() for e in s { switch e { case let a as [Any]: r += flatten(a) case let x as T: r.append(x) default: assert(false, "value of wrong type") } } return r } let s = list(list(1), 2, list(list(3, 4), 5), list(list(list())), list(list(list(6))), 7, 8, list() ) println(s) let result : [Int] = flatten(s) println(result)
import java.util.LinkedList; import java.util.List; public final class FlattenUtil { public static List<Object> flatten(List<?> list) { List<Object> retVal = new LinkedList<Object>(); flatten(list, retVal); return retVal; } public static void flatten(List<?> fromTreeList, List<Object> toFlatList) { for (Object item : fromTreeList) { if (item instanceof List<?>) { flatten((List<?>) item, toFlatList); } else { toFlatList.add(item); } } } }
Rewrite this program in Python while keeping its functionality equivalent to the Swift version.
func list(s: Any...) -> [Any] { return s } func flatten<T>(s: [Any]) -> [T] { var r = [T]() for e in s { switch e { case let a as [Any]: r += flatten(a) case let x as T: r.append(x) default: assert(false, "value of wrong type") } } return r } let s = list(list(1), 2, list(list(3, 4), 5), list(list(list())), list(list(list(6))), 7, 8, list() ) println(s) let result : [Int] = flatten(s) println(result)
>>> def flatten(lst): return sum( ([x] if not isinstance(x, list) else flatten(x) for x in lst), [] ) >>> lst = [[1], 2, [[3,4], 5], [[[]]], [[[6]]], 7, 8, []] >>> flatten(lst) [1, 2, 3, 4, 5, 6, 7, 8]
Produce a language-to-language conversion: from Swift to Python, same semantics.
func list(s: Any...) -> [Any] { return s } func flatten<T>(s: [Any]) -> [T] { var r = [T]() for e in s { switch e { case let a as [Any]: r += flatten(a) case let x as T: r.append(x) default: assert(false, "value of wrong type") } } return r } let s = list(list(1), 2, list(list(3, 4), 5), list(list(list())), list(list(list(6))), 7, 8, list() ) println(s) let result : [Int] = flatten(s) println(result)
>>> def flatten(lst): return sum( ([x] if not isinstance(x, list) else flatten(x) for x in lst), [] ) >>> lst = [[1], 2, [[3,4], 5], [[[]]], [[[6]]], 7, 8, []] >>> flatten(lst) [1, 2, 3, 4, 5, 6, 7, 8]
Keep all operations the same but rewrite the snippet in VB.
func list(s: Any...) -> [Any] { return s } func flatten<T>(s: [Any]) -> [T] { var r = [T]() for e in s { switch e { case let a as [Any]: r += flatten(a) case let x as T: r.append(x) default: assert(false, "value of wrong type") } } return r } let s = list(list(1), 2, list(list(3, 4), 5), list(list(list())), list(list(list(6))), 7, 8, list() ) println(s) let result : [Int] = flatten(s) println(result)
class flattener dim separator sub class_initialize separator = "," end sub private function makeflat( a ) dim i dim res for i = lbound( a ) to ubound( a ) if isarray( a( i ) ) then res = res & makeflat( a( i ) ) else res = res & a( i ) & separator end if next makeflat = res end function public function flatten( a ) dim res res = makeflat( a ) res = left( res, len( res ) - len(separator)) res = split( res, separator ) flatten = res end function public property let itemSeparator( c ) separator = c end property end class
Can you help me rewrite this code in VB instead of Swift, keeping it the same logically?
func list(s: Any...) -> [Any] { return s } func flatten<T>(s: [Any]) -> [T] { var r = [T]() for e in s { switch e { case let a as [Any]: r += flatten(a) case let x as T: r.append(x) default: assert(false, "value of wrong type") } } return r } let s = list(list(1), 2, list(list(3, 4), 5), list(list(list())), list(list(list(6))), 7, 8, list() ) println(s) let result : [Int] = flatten(s) println(result)
class flattener dim separator sub class_initialize separator = "," end sub private function makeflat( a ) dim i dim res for i = lbound( a ) to ubound( a ) if isarray( a( i ) ) then res = res & makeflat( a( i ) ) else res = res & a( i ) & separator end if next makeflat = res end function public function flatten( a ) dim res res = makeflat( a ) res = left( res, len( res ) - len(separator)) res = split( res, separator ) flatten = res end function public property let itemSeparator( c ) separator = c end property end class
Produce a functionally identical Go code for the snippet given in Swift.
func list(s: Any...) -> [Any] { return s } func flatten<T>(s: [Any]) -> [T] { var r = [T]() for e in s { switch e { case let a as [Any]: r += flatten(a) case let x as T: r.append(x) default: assert(false, "value of wrong type") } } return r } let s = list(list(1), 2, list(list(3, 4), 5), list(list(list())), list(list(list(6))), 7, 8, list() ) println(s) let result : [Int] = flatten(s) println(result)
package main import "fmt" func list(s ...interface{}) []interface{} { return s } func main() { s := list(list(1), 2, list(list(3, 4), 5), list(list(list())), list(list(list(6))), 7, 8, list(), ) fmt.Println(s) fmt.Println(flatten(s)) } func flatten(s []interface{}) (r []int) { for _, e := range s { switch i := e.(type) { case int: r = append(r, i) case []interface{}: r = append(r, flatten(i)...) } } return }
Change the programming language of this snippet from Swift to Go without modifying what it does.
func list(s: Any...) -> [Any] { return s } func flatten<T>(s: [Any]) -> [T] { var r = [T]() for e in s { switch e { case let a as [Any]: r += flatten(a) case let x as T: r.append(x) default: assert(false, "value of wrong type") } } return r } let s = list(list(1), 2, list(list(3, 4), 5), list(list(list())), list(list(list(6))), 7, 8, list() ) println(s) let result : [Int] = flatten(s) println(result)
package main import "fmt" func list(s ...interface{}) []interface{} { return s } func main() { s := list(list(1), 2, list(list(3, 4), 5), list(list(list())), list(list(list(6))), 7, 8, list(), ) fmt.Println(s) fmt.Println(flatten(s)) } func flatten(s []interface{}) (r []int) { for _, e := range s { switch i := e.(type) { case int: r = append(r, i) case []interface{}: r = append(r, flatten(i)...) } } return }
Generate a C translation of this Tcl snippet without changing its computational steps.
proc flatten list { for {set old {}} {$old ne $list} {} { set old $list set list [join $list] } return $list } puts [flatten {{1} 2 {{3 4} 5} {{{}}} {{{6}}} 7 8 {}}]
#include <stdio.h> #include <stdlib.h> #include <string.h> typedef struct list_t list_t, *list; struct list_t{ int is_list, ival; list *lst; }; list new_list() { list x = malloc(sizeof(list_t)); x->ival = 0; x->is_list = 1; x->lst = 0; return x; } void append(list parent, list child) { parent->lst = realloc(parent->lst, sizeof(list) * (parent->ival + 1)); parent->lst[parent->ival++] = child; } list from_string(char *s, char **e, list parent) { list ret = 0; if (!parent) parent = new_list(); while (*s != '\0') { if (*s == ']') { if (e) *e = s + 1; return parent; } if (*s == '[') { ret = new_list(); ret->is_list = 1; ret->ival = 0; append(parent, ret); from_string(s + 1, &s, ret); continue; } if (*s >= '0' && *s <= '9') { ret = new_list(); ret->is_list = 0; ret->ival = strtol(s, &s, 10); append(parent, ret); continue; } s++; } if (e) *e = s; return parent; } void show_list(list l) { int i; if (!l) return; if (!l->is_list) { printf("%d", l->ival); return; } printf("["); for (i = 0; i < l->ival; i++) { show_list(l->lst[i]); if (i < l->ival - 1) printf(", "); } printf("]"); } list flatten(list from, list to) { int i; list t; if (!to) to = new_list(); if (!from->is_list) { t = new_list(); *t = *from; append(to, t); } else for (i = 0; i < from->ival; i++) flatten(from->lst[i], to); return to; } void delete_list(list l) { int i; if (!l) return; if (l->is_list && l->ival) { for (i = 0; i < l->ival; i++) delete_list(l->lst[i]); free(l->lst); } free(l); } int main() { list l = from_string("[1], 2, [[3,4], 5], [[[]]], [[[6]]], 7, 8, []", 0, 0); printf("Nested: "); show_list(l); printf("\n"); list flat = flatten(l, 0); printf("Flattened: "); show_list(flat); return 0; }
Change the programming language of this snippet from Tcl to C without modifying what it does.
proc flatten list { for {set old {}} {$old ne $list} {} { set old $list set list [join $list] } return $list } puts [flatten {{1} 2 {{3 4} 5} {{{}}} {{{6}}} 7 8 {}}]
#include <stdio.h> #include <stdlib.h> #include <string.h> typedef struct list_t list_t, *list; struct list_t{ int is_list, ival; list *lst; }; list new_list() { list x = malloc(sizeof(list_t)); x->ival = 0; x->is_list = 1; x->lst = 0; return x; } void append(list parent, list child) { parent->lst = realloc(parent->lst, sizeof(list) * (parent->ival + 1)); parent->lst[parent->ival++] = child; } list from_string(char *s, char **e, list parent) { list ret = 0; if (!parent) parent = new_list(); while (*s != '\0') { if (*s == ']') { if (e) *e = s + 1; return parent; } if (*s == '[') { ret = new_list(); ret->is_list = 1; ret->ival = 0; append(parent, ret); from_string(s + 1, &s, ret); continue; } if (*s >= '0' && *s <= '9') { ret = new_list(); ret->is_list = 0; ret->ival = strtol(s, &s, 10); append(parent, ret); continue; } s++; } if (e) *e = s; return parent; } void show_list(list l) { int i; if (!l) return; if (!l->is_list) { printf("%d", l->ival); return; } printf("["); for (i = 0; i < l->ival; i++) { show_list(l->lst[i]); if (i < l->ival - 1) printf(", "); } printf("]"); } list flatten(list from, list to) { int i; list t; if (!to) to = new_list(); if (!from->is_list) { t = new_list(); *t = *from; append(to, t); } else for (i = 0; i < from->ival; i++) flatten(from->lst[i], to); return to; } void delete_list(list l) { int i; if (!l) return; if (l->is_list && l->ival) { for (i = 0; i < l->ival; i++) delete_list(l->lst[i]); free(l->lst); } free(l); } int main() { list l = from_string("[1], 2, [[3,4], 5], [[[]]], [[[6]]], 7, 8, []", 0, 0); printf("Nested: "); show_list(l); printf("\n"); list flat = flatten(l, 0); printf("Flattened: "); show_list(flat); return 0; }
Port the following code from Tcl to C# with equivalent syntax and logic.
proc flatten list { for {set old {}} {$old ne $list} {} { set old $list set list [join $list] } return $list } puts [flatten {{1} 2 {{3 4} 5} {{{}}} {{{6}}} 7 8 {}}]
using System; using System.Collections; using System.Linq; namespace RosettaCodeTasks { static class FlattenList { public static ArrayList Flatten(this ArrayList List) { ArrayList NewList = new ArrayList ( ); NewList.AddRange ( List ); while ( NewList.OfType<ArrayList> ( ).Count ( ) > 0 ) { int index = NewList.IndexOf ( NewList.OfType<ArrayList> ( ).ElementAt ( 0 ) ); ArrayList Temp = (ArrayList)NewList[index]; NewList.RemoveAt ( index ); NewList.InsertRange ( index, Temp ); } return NewList; } } }
Convert this Tcl block to C#, preserving its control flow and logic.
proc flatten list { for {set old {}} {$old ne $list} {} { set old $list set list [join $list] } return $list } puts [flatten {{1} 2 {{3 4} 5} {{{}}} {{{6}}} 7 8 {}}]
using System; using System.Collections; using System.Linq; namespace RosettaCodeTasks { static class FlattenList { public static ArrayList Flatten(this ArrayList List) { ArrayList NewList = new ArrayList ( ); NewList.AddRange ( List ); while ( NewList.OfType<ArrayList> ( ).Count ( ) > 0 ) { int index = NewList.IndexOf ( NewList.OfType<ArrayList> ( ).ElementAt ( 0 ) ); ArrayList Temp = (ArrayList)NewList[index]; NewList.RemoveAt ( index ); NewList.InsertRange ( index, Temp ); } return NewList; } } }
Write a version of this Tcl function in C++ with identical behavior.
proc flatten list { for {set old {}} {$old ne $list} {} { set old $list set list [join $list] } return $list } puts [flatten {{1} 2 {{3 4} 5} {{{}}} {{{6}}} 7 8 {}}]
#include <list> #include <boost/any.hpp> typedef std::list<boost::any> anylist; void flatten(std::list<boost::any>& list) { typedef anylist::iterator iterator; iterator current = list.begin(); while (current != list.end()) { if (current->type() == typeid(anylist)) { iterator next = current; ++next; list.splice(next, boost::any_cast<anylist&>(*current)); current = list.erase(current); } else ++current; } }
Convert this Tcl snippet to C++ and keep its semantics consistent.
proc flatten list { for {set old {}} {$old ne $list} {} { set old $list set list [join $list] } return $list } puts [flatten {{1} 2 {{3 4} 5} {{{}}} {{{6}}} 7 8 {}}]
#include <list> #include <boost/any.hpp> typedef std::list<boost::any> anylist; void flatten(std::list<boost::any>& list) { typedef anylist::iterator iterator; iterator current = list.begin(); while (current != list.end()) { if (current->type() == typeid(anylist)) { iterator next = current; ++next; list.splice(next, boost::any_cast<anylist&>(*current)); current = list.erase(current); } else ++current; } }
Port the provided Tcl code into Java while preserving the original functionality.
proc flatten list { for {set old {}} {$old ne $list} {} { set old $list set list [join $list] } return $list } puts [flatten {{1} 2 {{3 4} 5} {{{}}} {{{6}}} 7 8 {}}]
import java.util.LinkedList; import java.util.List; public final class FlattenUtil { public static List<Object> flatten(List<?> list) { List<Object> retVal = new LinkedList<Object>(); flatten(list, retVal); return retVal; } public static void flatten(List<?> fromTreeList, List<Object> toFlatList) { for (Object item : fromTreeList) { if (item instanceof List<?>) { flatten((List<?>) item, toFlatList); } else { toFlatList.add(item); } } } }
Port the provided Tcl code into Java while preserving the original functionality.
proc flatten list { for {set old {}} {$old ne $list} {} { set old $list set list [join $list] } return $list } puts [flatten {{1} 2 {{3 4} 5} {{{}}} {{{6}}} 7 8 {}}]
import java.util.LinkedList; import java.util.List; public final class FlattenUtil { public static List<Object> flatten(List<?> list) { List<Object> retVal = new LinkedList<Object>(); flatten(list, retVal); return retVal; } public static void flatten(List<?> fromTreeList, List<Object> toFlatList) { for (Object item : fromTreeList) { if (item instanceof List<?>) { flatten((List<?>) item, toFlatList); } else { toFlatList.add(item); } } } }
Port the following code from Tcl to Python with equivalent syntax and logic.
proc flatten list { for {set old {}} {$old ne $list} {} { set old $list set list [join $list] } return $list } puts [flatten {{1} 2 {{3 4} 5} {{{}}} {{{6}}} 7 8 {}}]
>>> def flatten(lst): return sum( ([x] if not isinstance(x, list) else flatten(x) for x in lst), [] ) >>> lst = [[1], 2, [[3,4], 5], [[[]]], [[[6]]], 7, 8, []] >>> flatten(lst) [1, 2, 3, 4, 5, 6, 7, 8]
Can you help me rewrite this code in Python instead of Tcl, keeping it the same logically?
proc flatten list { for {set old {}} {$old ne $list} {} { set old $list set list [join $list] } return $list } puts [flatten {{1} 2 {{3 4} 5} {{{}}} {{{6}}} 7 8 {}}]
>>> def flatten(lst): return sum( ([x] if not isinstance(x, list) else flatten(x) for x in lst), [] ) >>> lst = [[1], 2, [[3,4], 5], [[[]]], [[[6]]], 7, 8, []] >>> flatten(lst) [1, 2, 3, 4, 5, 6, 7, 8]
Please provide an equivalent version of this Tcl code in VB.
proc flatten list { for {set old {}} {$old ne $list} {} { set old $list set list [join $list] } return $list } puts [flatten {{1} 2 {{3 4} 5} {{{}}} {{{6}}} 7 8 {}}]
class flattener dim separator sub class_initialize separator = "," end sub private function makeflat( a ) dim i dim res for i = lbound( a ) to ubound( a ) if isarray( a( i ) ) then res = res & makeflat( a( i ) ) else res = res & a( i ) & separator end if next makeflat = res end function public function flatten( a ) dim res res = makeflat( a ) res = left( res, len( res ) - len(separator)) res = split( res, separator ) flatten = res end function public property let itemSeparator( c ) separator = c end property end class
Generate an equivalent VB version of this Tcl code.
proc flatten list { for {set old {}} {$old ne $list} {} { set old $list set list [join $list] } return $list } puts [flatten {{1} 2 {{3 4} 5} {{{}}} {{{6}}} 7 8 {}}]
class flattener dim separator sub class_initialize separator = "," end sub private function makeflat( a ) dim i dim res for i = lbound( a ) to ubound( a ) if isarray( a( i ) ) then res = res & makeflat( a( i ) ) else res = res & a( i ) & separator end if next makeflat = res end function public function flatten( a ) dim res res = makeflat( a ) res = left( res, len( res ) - len(separator)) res = split( res, separator ) flatten = res end function public property let itemSeparator( c ) separator = c end property end class
Generate an equivalent Go version of this Tcl code.
proc flatten list { for {set old {}} {$old ne $list} {} { set old $list set list [join $list] } return $list } puts [flatten {{1} 2 {{3 4} 5} {{{}}} {{{6}}} 7 8 {}}]
package main import "fmt" func list(s ...interface{}) []interface{} { return s } func main() { s := list(list(1), 2, list(list(3, 4), 5), list(list(list())), list(list(list(6))), 7, 8, list(), ) fmt.Println(s) fmt.Println(flatten(s)) } func flatten(s []interface{}) (r []int) { for _, e := range s { switch i := e.(type) { case int: r = append(r, i) case []interface{}: r = append(r, flatten(i)...) } } return }
Change the programming language of this snippet from Tcl to Go without modifying what it does.
proc flatten list { for {set old {}} {$old ne $list} {} { set old $list set list [join $list] } return $list } puts [flatten {{1} 2 {{3 4} 5} {{{}}} {{{6}}} 7 8 {}}]
package main import "fmt" func list(s ...interface{}) []interface{} { return s } func main() { s := list(list(1), 2, list(list(3, 4), 5), list(list(list())), list(list(list(6))), 7, 8, list(), ) fmt.Println(s) fmt.Println(flatten(s)) } func flatten(s []interface{}) (r []int) { for _, e := range s { switch i := e.(type) { case int: r = append(r, i) case []interface{}: r = append(r, flatten(i)...) } } return }
Translate the given Rust code snippet into PHP without altering its behavior.
use std::{vec, mem, iter}; enum List<T> { Node(Vec<List<T>>), Leaf(T), } impl<T> IntoIterator for List<T> { type Item = List<T>; type IntoIter = ListIter<T>; fn into_iter(self) -> Self::IntoIter { match self { List::Node(vec) => ListIter::NodeIter(vec.into_iter()), leaf @ List::Leaf(_) => ListIter::LeafIter(iter::once(leaf)), } } } enum ListIter<T> { NodeIter(vec::IntoIter<List<T>>), LeafIter(iter::Once<List<T>>), } impl<T> ListIter<T> { fn flatten(self) -> Flatten<T> { Flatten { stack: Vec::new(), curr: self, } } } impl<T> Iterator for ListIter<T> { type Item = List<T>; fn next(&mut self) -> Option<Self::Item> { match *self { ListIter::NodeIter(ref mut v_iter) => v_iter.next(), ListIter::LeafIter(ref mut o_iter) => o_iter.next(), } } } struct Flatten<T> { stack: Vec<ListIter<T>>, curr: ListIter<T>, } impl<T> Iterator for Flatten<T> { type Item = T; fn next(&mut self) -> Option<Self::Item> { loop { match self.curr.next() { Some(list) => { match list { node @ List::Node(_) => { self.stack.push(node.into_iter()); let len = self.stack.len(); mem::swap(&mut self.stack[len - 1], &mut self.curr); } List::Leaf(item) => return Some(item), } } None => { if let Some(next) = self.stack.pop() { self.curr = next; } else { return None; } } } } } } use List::*; fn main() { let list = Node(vec![Node(vec![Leaf(1)]), Leaf(2), Node(vec![Node(vec![Leaf(3), Leaf(4)]), Leaf(5)]), Node(vec![Node(vec![Node(vec![])])]), Node(vec![Node(vec![Node(vec![Leaf(6)])])]), Leaf(7), Leaf(8), Node(vec![])]); for elem in list.into_iter().flatten() { print!("{} ", elem); } println!(); }
while (array_filter($lst, 'is_array')) $lst = call_user_func_array('array_merge', $lst);
Write the same code in PHP as shown below in Rust.
use std::{vec, mem, iter}; enum List<T> { Node(Vec<List<T>>), Leaf(T), } impl<T> IntoIterator for List<T> { type Item = List<T>; type IntoIter = ListIter<T>; fn into_iter(self) -> Self::IntoIter { match self { List::Node(vec) => ListIter::NodeIter(vec.into_iter()), leaf @ List::Leaf(_) => ListIter::LeafIter(iter::once(leaf)), } } } enum ListIter<T> { NodeIter(vec::IntoIter<List<T>>), LeafIter(iter::Once<List<T>>), } impl<T> ListIter<T> { fn flatten(self) -> Flatten<T> { Flatten { stack: Vec::new(), curr: self, } } } impl<T> Iterator for ListIter<T> { type Item = List<T>; fn next(&mut self) -> Option<Self::Item> { match *self { ListIter::NodeIter(ref mut v_iter) => v_iter.next(), ListIter::LeafIter(ref mut o_iter) => o_iter.next(), } } } struct Flatten<T> { stack: Vec<ListIter<T>>, curr: ListIter<T>, } impl<T> Iterator for Flatten<T> { type Item = T; fn next(&mut self) -> Option<Self::Item> { loop { match self.curr.next() { Some(list) => { match list { node @ List::Node(_) => { self.stack.push(node.into_iter()); let len = self.stack.len(); mem::swap(&mut self.stack[len - 1], &mut self.curr); } List::Leaf(item) => return Some(item), } } None => { if let Some(next) = self.stack.pop() { self.curr = next; } else { return None; } } } } } } use List::*; fn main() { let list = Node(vec![Node(vec![Leaf(1)]), Leaf(2), Node(vec![Node(vec![Leaf(3), Leaf(4)]), Leaf(5)]), Node(vec![Node(vec![Node(vec![])])]), Node(vec![Node(vec![Node(vec![Leaf(6)])])]), Leaf(7), Leaf(8), Node(vec![])]); for elem in list.into_iter().flatten() { print!("{} ", elem); } println!(); }
while (array_filter($lst, 'is_array')) $lst = call_user_func_array('array_merge', $lst);
Can you help me rewrite this code in PHP instead of Ada, keeping it the same logically?
generic type Element_Type is private; with function To_String (E : Element_Type) return String is <>; package Nestable_Lists is type Node_Kind is (Data_Node, List_Node); type Node (Kind : Node_Kind); type List is access Node; type Node (Kind : Node_Kind) is record Next : List; case Kind is when Data_Node => Data : Element_Type; when List_Node => Sublist : List; end case; end record; procedure Append (L : in out List; E : Element_Type); procedure Append (L : in out List; N : List); function Flatten (L : List) return List; function New_List (E : Element_Type) return List; function New_List (N : List) return List; function To_String (L : List) return String; end Nestable_Lists;
while (array_filter($lst, 'is_array')) $lst = call_user_func_array('array_merge', $lst);
Write the same algorithm in PHP as shown in this Ada implementation.
generic type Element_Type is private; with function To_String (E : Element_Type) return String is <>; package Nestable_Lists is type Node_Kind is (Data_Node, List_Node); type Node (Kind : Node_Kind); type List is access Node; type Node (Kind : Node_Kind) is record Next : List; case Kind is when Data_Node => Data : Element_Type; when List_Node => Sublist : List; end case; end record; procedure Append (L : in out List; E : Element_Type); procedure Append (L : in out List; N : List); function Flatten (L : List) return List; function New_List (E : Element_Type) return List; function New_List (N : List) return List; function To_String (L : List) return String; end Nestable_Lists;
while (array_filter($lst, 'is_array')) $lst = call_user_func_array('array_merge', $lst);
Port the provided Arturo code into PHP while preserving the original functionality.
print flatten [[1], 2, [[3, 4], 5], [[[]]], [[[6]]], 7, 8, []]
while (array_filter($lst, 'is_array')) $lst = call_user_func_array('array_merge', $lst);
Preserve the algorithm and functionality while converting the code from Arturo to PHP.
print flatten [[1], 2, [[3, 4], 5], [[[]]], [[[6]]], 7, 8, []]
while (array_filter($lst, 'is_array')) $lst = call_user_func_array('array_merge', $lst);
Generate an equivalent PHP version of this AutoHotKey code.
list := object(1, object(1, 1), 2, 2, 3, object(1, object(1, 3, 2, 4) , 2, 5), 4, object(1, object(1, object(1, object()))), 5 , object(1, object(1, 6)), 6, 7, 7, 8, 9, object()) msgbox % objPrint(list)  msgbox % objPrint(objFlatten(list))  return !r::reload !q::exitapp objPrint(ast, reserved=0) { if !isobject(ast) return " " ast " " if !reserved reserved := object("seen" . &ast, 1)   enum := ast._newenum() while enum[key, value] { if reserved["seen" . &value] continue   string .= objPrint(value, reserved) } return "(" string ")" } objFlatten(ast) { if !isobject(ast) return ast flat := object()  enum := ast._newenum() while enum[key, value] { if !isobject(value) flat._Insert(value) else { next := objFlatten(value) loop % next._MaxIndex() flat._Insert(next[A_Index]) } } return flat }
while (array_filter($lst, 'is_array')) $lst = call_user_func_array('array_merge', $lst);
Translate the given AutoHotKey code snippet into PHP without altering its behavior.
list := object(1, object(1, 1), 2, 2, 3, object(1, object(1, 3, 2, 4) , 2, 5), 4, object(1, object(1, object(1, object()))), 5 , object(1, object(1, 6)), 6, 7, 7, 8, 9, object()) msgbox % objPrint(list)  msgbox % objPrint(objFlatten(list))  return !r::reload !q::exitapp objPrint(ast, reserved=0) { if !isobject(ast) return " " ast " " if !reserved reserved := object("seen" . &ast, 1)   enum := ast._newenum() while enum[key, value] { if reserved["seen" . &value] continue   string .= objPrint(value, reserved) } return "(" string ")" } objFlatten(ast) { if !isobject(ast) return ast flat := object()  enum := ast._newenum() while enum[key, value] { if !isobject(value) flat._Insert(value) else { next := objFlatten(value) loop % next._MaxIndex() flat._Insert(next[A_Index]) } } return flat }
while (array_filter($lst, 'is_array')) $lst = call_user_func_array('array_merge', $lst);
Port the provided Clojure code into PHP while preserving the original functionality.
(defn flatten [lst] (sum (genexpr (if (isinstance x list) (flatten x) [x]) [x lst]) [])) (print (flatten [[1] 2 [[3 4] 5] [[[]]] [[[6]]] 7 8 []]))
while (array_filter($lst, 'is_array')) $lst = call_user_func_array('array_merge', $lst);
Keep all operations the same but rewrite the snippet in PHP.
(defn flatten [lst] (sum (genexpr (if (isinstance x list) (flatten x) [x]) [x lst]) [])) (print (flatten [[1] 2 [[3 4] 5] [[[]]] [[[6]]] 7 8 []]))
while (array_filter($lst, 'is_array')) $lst = call_user_func_array('array_merge', $lst);
Transform the following Common_Lisp implementation into PHP, maintaining the same output and logic.
(defun flatten (tr) (cond ((null tr) nil) ((atom tr) (list tr)) (t (append (flatten (first tr)) (flatten (rest tr))))))
while (array_filter($lst, 'is_array')) $lst = call_user_func_array('array_merge', $lst);