Instruction stringlengths 45 106 | input_code stringlengths 1 13.7k | output_code stringlengths 1 13.7k |
|---|---|---|
Write the same code in Common_Lisp as shown below in VB. | Module Module1
Sub Print(ls As List(Of Integer))
Dim iter = ls.GetEnumerator
Console.Write("[")
If iter.MoveNext Then
Console.Write(iter.Current)
End If
While iter.MoveNext
Console.Write(", ")
Console.Write(iter.Current)
End While
... |
(defmacro kaprekar-number-filter (n &optional (base 10))
`(= (mod ,n (1- ,base)) (mod (* ,n ,n) (1- ,base))))
(defun test (&key (start 1) (stop 10000) (base 10) (collect t))
(let ((count 0)
(nums))
(loop for i from start to stop do
(when (kaprekar-number-filter i base)
(if collect (push i nums))
... |
Port the following code from VB to Common_Lisp with equivalent syntax and logic. | suite$ = "CDHS" #Club, Diamond, Heart, Spade
card$ = "A23456789TJQK" #Cards Ace to King
card = 0
dim n(55) #make ordered deck
for i = 1 to 52 # of 52 cards
n[i] = i
next i
for i = 1 to 52 * 3 #shuffle deck 3 times
i1 = int(rand * 5... | (defun remove-nth (i xs)
(if (or (zp i) (endp (rest xs)))
(rest xs)
(cons (first xs)
(remove-nth (1- i) (rest xs)))))
(defthm remove-nth-shortens
(implies (consp xs)
(< (len (remove-nth i xs)) (len xs))))
:set-state-ok t
(defun shuffle-r (xs ys state)
(declare (xargs :... |
Convert this VB block to Common_Lisp, preserving its control flow and logic. | Module Module1
Dim r As New Random
Function getThree(n As Integer) As List(Of Integer)
getThree = New List(Of Integer)
For i As Integer = 1 To 4 : getThree.Add(r.Next(n) + 1) : Next
getThree.Sort() : getThree.RemoveAt(0)
End Function
Function getSix() As List(Of Integer)
... | (defpackage :rpg-generator
(:use :cl)
(:export :generate))
(in-package :rpg-generator)
(defun sufficient-scores-p (scores)
(and (>= (apply #'+ scores) 75)
(>= (count-if #'(lambda (n) (>= n 15)) scores) 2)))
(defun gen-score ()
(apply #'+ (rest (sort (loop repeat 4 collect (1+ (random 6))) #'<))))
(defu... |
Maintain the same structure and functionality when rewriting this code in Common_Lisp. |
sub ensure_cscript()
if instrrev(ucase(WScript.FullName),"WSCRIPT.EXE")then
createobject("wscript.shell").run "CSCRIPT //nologo """ &_
WScript.ScriptFullName &"""" ,,0
wscript.quit
end if
end sub
class bargraph
private bar,mn,mx,nn,cnt
Private sub class_initialize()
bar=chrw(&h2581)&chrw(&h258... | (defun buckets (numbers)
(loop with min = (apply #'min numbers)
with max = (apply #'max numbers)
with width = (/ (- max min) 7)
for base from (- min (/ width 2)) by width
repeat 8
collect (cons base (+ base width))))
(defun bucket-for-number (number buckets)
(loop for i from... |
Produce a language-to-language conversion: from VB to Common_Lisp, same semantics. | Sub Lis(arr() As Integer)
Dim As Integer lb = Lbound(arr), ub = Ubound(arr)
Dim As Integer i, lo, hi, mitad, newl, l = 0
Dim As Integer p(ub), m(ub)
For i = lb To ub
lo = 1
hi = l
Do While lo <= hi
mitad = Int((lo+hi)/2)
If arr(m(mitad)) < arr(i) Then
lo = mitad + 1
Else
h... | (defun longest-increasing-subseq (list)
(let ((subseqs nil))
(dolist (item list)
(let ((longest-so-far (longest-list-in-lists (remove-if-not #'(lambda (l) (> item (car l))) subseqs))))
(push (cons item longest-so-far) subseqs)))
(reverse (longest-list-in-lists subseqs))))
(defun longest-list-in-lists ... |
Ensure the translated Common_Lisp code behaves exactly like the original VB snippet. | #macro assign(sym, expr)
__fb_unquote__(__fb_eval__("#undef " + sym))
__fb_unquote__(__fb_eval__("#define " + sym + " " + __fb_quote__(__fb_eval__(expr))))
#endmacro
#define a, b, x
assign("a", 8)
assign("b", 7)
assign("x", Sqr(a) + (Sin(b*3)/2))
Print x
assign("x", "goodbye")
Print x
Sleep
| (eval '(+ 4 5))
|
Change the programming language of this snippet from VB to Common_Lisp without modifying what it does. | #macro assign(sym, expr)
__fb_unquote__(__fb_eval__("#undef " + sym))
__fb_unquote__(__fb_eval__("#define " + sym + " " + __fb_quote__(__fb_eval__(expr))))
#endmacro
#define a, b, x
assign("a", 8)
assign("b", 7)
assign("x", Sqr(a) + (Sin(b*3)/2))
Print x
assign("x", "goodbye")
Print x
Sleep
| (eval '(+ 4 5))
|
Write the same code in Common_Lisp as shown below in VB. | Module Module1
Function GetGroup(s As String, depth As Integer) As Tuple(Of List(Of String), String)
Dim out As New List(Of String)
Dim comma = False
While Not String.IsNullOrEmpty(s)
Dim gs = GetItem(s, depth)
Dim g = gs.Item1
s = gs.Item2
If... | (defstruct alternation
(alternatives nil :type list))
(defun alternatives-end-positions (string start)
(assert (char= (char string start) #\{))
(loop with level = 0
with end-positions
with escapep and commap
for index from start below (length string)
for c = (char string index)
... |
Please provide an equivalent version of this VB code in Common_Lisp. | Private Function GetPixelColor(ByVal Location As Point) As Color
Dim b As New Bitmap(1, 1)
Dim g As Graphics = Graphics.FromImage(b)
g.CopyFromScreen(Location, Point.Empty, New Size(1, 1))
Return b.GetPixel(0, 0)
End Function
| (defn get-color-at [x y]
(.getPixelColor (java.awt.Robot.) x y))
|
Transform the following VB implementation into Common_Lisp, maintaining the same output and logic. | Option Explicit
Private Declare Sub Sleep Lib "kernel32" (ByVal dwMilliseconds As Long)
Private Const HT As String = "H T"
Public Sub PenneysGame()
Dim S$, YourSeq$, ComputeSeq$, i&, Seq$, WhoWin$, flag As Boolean
Do
S = WhoWillBeFirst(Choice("Who will be first"))
If S = "ABORT" Then Exit Do
... | (setf *random-state* (make-random-state t))
(defparameter *heads* #\H)
(defparameter *tails* #\T)
(defun main ()
(format t "Penney's Game~%~%")
(format t "Flipping to see who goes first ...")
(setq p2 nil)
(if (string= (flip) *heads*)
(progn (format t " I do.~%")
(setq p2 (choose-random-se... |
Keep all operations the same but rewrite the snippet in Common_Lisp. | Option Explicit
Declare Function Beep Lib "kernel32" (ByVal Freq As Long, ByVal Dur As Long) As Long
Sub Musical_Scale()
Dim Fqs, i As Integer
Fqs = Array(264, 297, 330, 352, 396, 440, 495, 528)
For i = LBound(Fqs) To UBound(Fqs)
Beep Fqs(i), 500
Next
End Sub
| (defun play-scale (freq-list dur)
"Play a list of frequencies."
(setq header (unibyte-string
46 115 110 100
0 0 0 24
255 255 255 255
0 0 0 3
0 0 172 68
0 0 0 1))
... |
Write a version of this VB function in Common_Lisp with identical behavior. | Option Explicit
Declare Function Beep Lib "kernel32" (ByVal Freq As Long, ByVal Dur As Long) As Long
Sub Musical_Scale()
Dim Fqs, i As Integer
Fqs = Array(264, 297, 330, 352, 396, 440, 495, 528)
For i = LBound(Fqs) To UBound(Fqs)
Beep Fqs(i), 500
Next
End Sub
| (defun play-scale (freq-list dur)
"Play a list of frequencies."
(setq header (unibyte-string
46 115 110 100
0 0 0 24
255 255 255 255
0 0 0 3
0 0 172 68
0 0 0 1))
... |
Convert this VB block to Common_Lisp, preserving its control flow and logic. | Set objXMLDoc = CreateObject("msxml2.domdocument")
objXMLDoc.load("In.xml")
Set item_nodes = objXMLDoc.selectNodes("//item")
i = 1
For Each item In item_nodes
If i = 1 Then
WScript.StdOut.Write item.xml
WScript.StdOut.WriteBlankLines(2)
Exit For
End If
Next
Set price_nodes = objXMLDoc.selectNodes("//price")
... | (dolist (system '(:xpath :cxml-stp :cxml))
(asdf:oos 'asdf:load-op system))
(defparameter *doc* (cxml:parse-file "xml" (stp:make-builder)))
(xpath:first-node (xpath:evaluate "/inventory/section[1]/item[1]" *doc*))
(xpath:do-node-set (node (xpath:evaluate "/inventory/section/item/price/text()" *doc*))
(format t "... |
Convert the following code from VB to Common_Lisp, ensuring the logic remains intact. | Set objFSO = CreateObject("Scripting.FileSystemObject")
Set srcFile = objFSO.OpenTextFile(objFSO.GetParentFolderName(WScript.ScriptFullName) &_
"\unixdict.txt",1,False,0)
cei = 0 : cie = 0 : ei = 0 : ie = 0
Do Until srcFile.AtEndOfStream
word = srcFile.ReadLine
If InStr(word,"cei") Then
cei = cei + 1
ElseIf In... | (defun test-rule (rule-name examples counter-examples)
(let ((plausible (if (> examples (* 2 counter-examples)) 'plausible 'not-plausible)))
(list rule-name plausible examples counter-examples)))
(defun plausibility (result-string file parser)
(let ((cei 0) (cie 0) (ie 0) (ei 0))
(macrolet ((search-count (... |
Produce a functionally identical Common_Lisp code for the snippet given in VB. | Set objFSO = CreateObject("Scripting.FileSystemObject")
Set srcFile = objFSO.OpenTextFile(objFSO.GetParentFolderName(WScript.ScriptFullName) &_
"\unixdict.txt",1,False,0)
cei = 0 : cie = 0 : ei = 0 : ie = 0
Do Until srcFile.AtEndOfStream
word = srcFile.ReadLine
If InStr(word,"cei") Then
cei = cei + 1
ElseIf In... | (defun test-rule (rule-name examples counter-examples)
(let ((plausible (if (> examples (* 2 counter-examples)) 'plausible 'not-plausible)))
(list rule-name plausible examples counter-examples)))
(defun plausibility (result-string file parser)
(let ((cei 0) (cie 0) (ie 0) (ei 0))
(macrolet ((search-count (... |
Preserve the algorithm and functionality while converting the code from VB to Common_Lisp. | Private Function ordinal(s As String) As String
Dim irregs As New Collection
irregs.Add "first", "one"
irregs.Add "second", "two"
irregs.Add "third", "three"
irregs.Add "fifth", "five"
irregs.Add "eighth", "eight"
irregs.Add "ninth", "nine"
irregs.Add "twelfth", "twelve"
Dim i As Int... | (defun ordinal-number (n)
(format nil "~:R" n))
|
Ensure the translated Common_Lisp code behaves exactly like the original VB snippet. | Public Sub backup(filename As String)
If Len(Dir(filename)) > 0 Then
On Error Resume Next
Name filename As filename & ".bak"
Else
If Len(Dir(filename & ".lnk")) > 0 Then
On Error Resume Next
With CreateObject("Wscript.Shell").CreateShortcut(filename & ".lnk")
... | (defun parse-integer-quietly (&rest args)
(ignore-errors (apply #'parse-integer args)))
(defun get-next-version (basename)
(flet ((parse-version (pathname)
(or (parse-integer-quietly
(string-left-trim (file-namestring basename)
... |
Change the following VB code into Common_Lisp without altering its purpose. | Public Sub backup(filename As String)
If Len(Dir(filename)) > 0 Then
On Error Resume Next
Name filename As filename & ".bak"
Else
If Len(Dir(filename & ".lnk")) > 0 Then
On Error Resume Next
With CreateObject("Wscript.Shell").CreateShortcut(filename & ".lnk")
... | (defun parse-integer-quietly (&rest args)
(ignore-errors (apply #'parse-integer args)))
(defun get-next-version (basename)
(flet ((parse-version (pathname)
(or (parse-integer-quietly
(string-left-trim (file-namestring basename)
... |
Translate the given VB code snippet into Common_Lisp without altering its behavior. | Dim dblDistance as Double
| (defvar *language* :en
"The language to use for messages (defaults to English)")
(defmacro with-language ((language) &body body)
"Locally binds *LANGUAGE* to LANGUAGE"
`(let ((*language* ,language))
,@body))
(defgeneric complain% (language about)
(:method ((language (eql :en)) (about (eql :weather)))
... |
Convert the following code from VB to Common_Lisp, ensuring the logic remains intact. | Function farey(n As Long, descending As Long) As Long
Dim a, b, c, d, k As Long
Dim aa, bb, cc, dd, count As Long
b = 1
c = 1
d = n
count = 0
If descending = True Then
a = 1
c = n - 1
End If
count += 1
If n < 12 Then Print Str(a); "/"; Str(b); " ";
While ((c <= n) And... | (defun farey (n)
(labels ((helper (begin end)
(let ((med (/ (+ (numerator begin) (numerator end))
(+ (denominator begin) (denominator end)))))
(if (<= (denominator med) n)
(append (helper begin med)
(list med)
(helper med end))))))
(append (list 0) (helper 0 1) (list 1))))
... |
Translate this program into Common_Lisp but keep the logic exactly as in VB. | Function farey(n As Long, descending As Long) As Long
Dim a, b, c, d, k As Long
Dim aa, bb, cc, dd, count As Long
b = 1
c = 1
d = n
count = 0
If descending = True Then
a = 1
c = n - 1
End If
count += 1
If n < 12 Then Print Str(a); "/"; Str(b); " ";
While ((c <= n) And... | (defun farey (n)
(labels ((helper (begin end)
(let ((med (/ (+ (numerator begin) (numerator end))
(+ (denominator begin) (denominator end)))))
(if (<= (denominator med) n)
(append (helper begin med)
(list med)
(helper med end))))))
(append (list 0) (helper 0 1) (list 1))))
... |
Convert the following code from VB to Common_Lisp, ensuring the logic remains intact. | Option Explicit
Private Type Aliquot
Sequence() As Double
Classification As String
End Type
Sub Main()
Dim result As Aliquot, i As Long, j As Double, temp As String
For j = 1 To 10
result = Aliq(j)
temp = vbNullString
For i = 0 To UBound(result.Sequence)
temp = temp & result.Seque... | (defparameter *nlimit* 16)
(defparameter *klimit* (expt 2 47))
(defparameter *asht* (make-hash-table))
(load "proper-divisors")
(defun ht-insert (v n)
(setf (gethash v *asht*) n))
(defun ht-find (v n)
(let ((nprev (gethash v *asht*)))
(if nprev (- n nprev) nil)))
(defun ht-list ()
(defun sort-keys (&optio... |
Can you help me rewrite this code in Common_Lisp instead of VB, keeping it the same logically? | Option Explicit
Private Type Aliquot
Sequence() As Double
Classification As String
End Type
Sub Main()
Dim result As Aliquot, i As Long, j As Double, temp As String
For j = 1 To 10
result = Aliq(j)
temp = vbNullString
For i = 0 To UBound(result.Sequence)
temp = temp & result.Seque... | (defparameter *nlimit* 16)
(defparameter *klimit* (expt 2 47))
(defparameter *asht* (make-hash-table))
(load "proper-divisors")
(defun ht-insert (v n)
(setf (gethash v *asht*) n))
(defun ht-find (v n)
(let ((nprev (gethash v *asht*)))
(if nprev (- n nprev) nil)))
(defun ht-list ()
(defun sort-keys (&optio... |
Convert this VB block to Common_Lisp, preserving its control flow and logic. | Dim t_age(4,1)
t_age(0,0) = 27 : t_age(0,1) = "Jonah"
t_age(1,0) = 18 : t_age(1,1) = "Alan"
t_age(2,0) = 28 : t_age(2,1) = "Glory"
t_age(3,0) = 18 : t_age(3,1) = "Popeye"
t_age(4,0) = 28 : t_age(4,1) = "Alan"
Dim t_nemesis(4,1)
t_nemesis(0,0) = "Jonah" : t_nemesis(0,1) = "Whales"
t_nemesis(1,0) = "Jonah" : t_nemesis(1... | (defparameter *table-A* '((27 "Jonah") (18 "Alan") (28 "Glory") (18 "Popeye") (28 "Alan")))
(defparameter *table-B* '(("Jonah" "Whales") ("Jonah" "Spiders") ("Alan" "Ghosts") ("Alan" "Zombies") ("Glory" "Buffy")))
(defparameter *hash-table* (make-hash-table :test #'equal))
(loop for (i r) in *table-A*
for value... |
Convert the following code from VB to Common_Lisp, ensuring the logic remains intact. | Sub InsertaElto(lista() As String, posic As Integer = 1)
For i As Integer = Lbound(lista) To Ubound(lista)
If i = posic Then Swap lista(i), lista(Ubound(lista))
Next i
End Sub
Sub mostrarLista(lista() As String, titulo As String)
Print !"\n"; titulo;
For i As Integer = Lbound(lista) To Ubo... | (defstruct dlist head tail)
(defstruct dlink content prev next)
(defun insert-between (dlist before after data)
"Insert a fresh link containing DATA after existing link BEFORE if not nil and before existing link AFTER if not nil"
(let ((new-link (make-dlink :content data :prev before :next after)))
(if (null b... |
Change the following VB code into Common_Lisp without altering its purpose. |
Type mina
Dim mina As Byte
Dim flag As Byte
Dim ok As Byte
Dim numero As Byte
End Type
Dim Shared As Integer size = 16, NX = 20, NY = 20
Dim Shared As Double mina = 0.10
Dim Shared tablero(NX+1,NY+1) As mina
Dim Shared As Integer GameOver, ddx, ddy, kolor, nbDESCANSO
Dim Shared As Double temp... | (defclass minefield ()
((mines :initform (make-hash-table :test #'equal))
(width :initarg :width)
(height :initarg :height)
(grid :initarg :grid)))
(defun make-minefield (width height num-mines)
(let ((minefield (make-instance 'minefield
:width width
... |
Translate the given VB code snippet into Common_Lisp without altering its behavior. |
dim i,j
Wscript.StdOut.WriteLine "-- Long Integer - Permutations - from 1 to 12"
for i=1 to 12
for j=1 to i
Wscript.StdOut.Write "P(" & i & "," & j & ")=" & perm(i,j) & " "
next
Wscript.StdOut.WriteLine ""
next
Wscript.StdOut.WriteLine "-- Float integer - Combinations from 10 to 60"
for i=10 to 60 step 10
f... | (defun combinations (n k)
(cond ((or (< n k) (< k 0) (< n 0)) 0)
((= k 0) 1)
(t (do* ((i 1 (1+ i))
(m n (1- m))
(a m (* a m))
(b i (* b i)))
((= i k) (/ a b))))))
(defun permutations (n k)
(cond ((or (< n k) (< k 0) (< n 0)) 0)
((= k 0) 1)
(t (do* ((i 1 (1+ i))
(m n (1- m))
(a m (* a m))... |
Change the following VB code into Common_Lisp without altering its purpose. | Dim As Short digits = 500
Dim As Double an = 1
Dim As Double bn = Sqr(0.5)
Dim As Double tn = 0.5^2
Dim As Double pn = 1
Dim As Double prevAn
While pn <= digits
prevAn = an
an = (bn + an) / 2
bn = Sqr(bn * prevAn)
prevAn -= an
tn -= (pn * prevAn^2)
pn *= 2
Wend
Dim As Double pi = ((an + bn)^2) ... | (ns async-example.core
(:use [criterium.core])
(:gen-class))
(import '(org.apfloat Apfloat ApfloatMath))
(def precision 8192)
(def one (Apfloat. 1M precision))
(def two (Apfloat. 2M precision))
(def four (Apfloat. 4M precision))
(def half (Apfloat. 0.5M precision))
(def quarter (Apfloat. 0.25M precision))
(def... |
Rewrite this program in Common_Lisp while keeping its functionality equivalent to the VB version. | Dim As Short digits = 500
Dim As Double an = 1
Dim As Double bn = Sqr(0.5)
Dim As Double tn = 0.5^2
Dim As Double pn = 1
Dim As Double prevAn
While pn <= digits
prevAn = an
an = (bn + an) / 2
bn = Sqr(bn * prevAn)
prevAn -= an
tn -= (pn * prevAn^2)
pn *= 2
Wend
Dim As Double pi = ((an + bn)^2) ... | (ns async-example.core
(:use [criterium.core])
(:gen-class))
(import '(org.apfloat Apfloat ApfloatMath))
(def precision 8192)
(def one (Apfloat. 1M precision))
(def two (Apfloat. 2M precision))
(def four (Apfloat. 4M precision))
(def half (Apfloat. 0.5M precision))
(def quarter (Apfloat. 0.25M precision))
(def... |
Convert this VB snippet to Common_Lisp and keep its semantics consistent. | Imports System, System.Collections.Generic, System.Linq, System.Console
Module LongPrimes
Function Period(ByVal n As Integer) As Integer
Dim m As Integer, r As Integer = 1
For i As Integer = 0 To n : r = 10 * r Mod n : Next
m = r : Period = 1 : While True
r = (10 * r) Mod n : I... |
(defun primep (n)
(cond ((and (<= n 3) (> n 1)) t)
((some #'zerop (mapcar (lambda (d) (mod n d)) '(2 3))) nil)
(t (loop for i = 5 then (+ i 6)
while (<= (* i i) n)
when (some #'zerop (mapcar (lambda (d) (mod n (+ i d))) '(0 2))) return nil
finally (re... |
Maintain the same structure and functionality when rewriting this code in Common_Lisp. | Function Biorhythm(Birthdate As Date, Targetdate As Date) As String
TextArray = Array(Array("up and rising", "peak"), Array("up but falling", "transition"), Array("down and falling", "valley"), Array("down but rising", "transition"))
DaysBetween = Targetdate - Birthdate
positionP = DaysBetween Mod 23
positionE = Da... |
(defun day (y m d)
(+ (truncate (* -7 (+ y (truncate (+ m 9) 12))) 4)
(truncate (* 275 m) 9) d -730530 (* 367 y)))
(defun diffday (y1 m1 d1 y2 m2 d2)
(abs (- (day y2 m2 d2) (day y1 m1 d1))))
(defun print-cycle (diff len nm)
(let ((perc (round (* 100 (sin (* 2 pi diff (/ 1 len)))))))
... |
Can you help me rewrite this code in Common_Lisp instead of VB, keeping it the same logically? | Function Biorhythm(Birthdate As Date, Targetdate As Date) As String
TextArray = Array(Array("up and rising", "peak"), Array("up but falling", "transition"), Array("down and falling", "valley"), Array("down but rising", "transition"))
DaysBetween = Targetdate - Birthdate
positionP = DaysBetween Mod 23
positionE = Da... |
(defun day (y m d)
(+ (truncate (* -7 (+ y (truncate (+ m 9) 12))) 4)
(truncate (* 275 m) 9) d -730530 (* 367 y)))
(defun diffday (y1 m1 d1 y2 m2 d2)
(abs (- (day y2 m2 d2) (day y1 m1 d1))))
(defun print-cycle (diff len nm)
(let ((perc (round (* 100 (sin (* 2 pi diff (/ 1 len)))))))
... |
Generate an equivalent Common_Lisp version of this VB code. | Imports System.Numerics
Imports System.Text
Module Module1
Function Gcd(a As BigInteger, b As BigInteger) As BigInteger
If b = 0 Then
If a < 0 Then
Return -a
Else
Return a
End If
Else
Return Gcd(b, a Mod b)
End... | (defun egyption-fractions (x y &optional acc)
(let* ((a (/ x y)))
(cond
((> (numerator a) (denominator a))
(multiple-value-bind (q r) (floor x y)
(if (zerop r)
(cons q acc)
(egyption-fractions r y (cons q acc)))))
((= (numerator a) 1) (reverse (cons a acc)))
(t (let ((b (ceiling y ... |
Change the following VB code into Common_Lisp without altering its purpose. | Imports System.Numerics
Imports System.Text
Module Module1
Function Gcd(a As BigInteger, b As BigInteger) As BigInteger
If b = 0 Then
If a < 0 Then
Return -a
Else
Return a
End If
Else
Return Gcd(b, a Mod b)
End... | (defun egyption-fractions (x y &optional acc)
(let* ((a (/ x y)))
(cond
((> (numerator a) (denominator a))
(multiple-value-bind (q r) (floor x y)
(if (zerop r)
(cons q acc)
(egyption-fractions r y (cons q acc)))))
((= (numerator a) 1) (reverse (cons a acc)))
(t (let ((b (ceiling y ... |
Convert this VB block to Common_Lisp, preserving its control flow and logic. | function isprime(v)
if v mod 2 = 0 then return v = 2
for d = 3 To Int(Sqr(v))+1 Step 2
if v mod d = 0 then return false
next d3
return True
end function
function diff_cubes(n)
return 3*n*(n+1) + 1
end function
function padto(n, s)
outstr = ""
k = length(string(n))
for i = 1 to s-k
outstr = " " + outstr
n... |
(defun primep (n)
(cond ((< n 4) t)
((evenp n) nil)
((zerop (mod n 3)) nil)
(t (loop for i from 5 upto (isqrt n) by 6
when (or
(zerop (mod n i))
(zerop (mod n (+ i 2))))
return nil
finally (return t)))))
... |
Convert the following code from VB to Common_Lisp, ensuring the logic remains intact. | Imports System.Text
Module Module1
Dim games As New List(Of String) From {"12", "13", "14", "23", "24", "34"}
Dim results = "000000"
Function FromBase3(num As String) As Integer
Dim out = 0
For Each c In num
Dim d = Asc(c) - Asc("0"c)
out = 3 * out + d
Next... | (defun histo ()
(let ((scoring (vector 0 1 3))
(histo (list (vector 0 0 0 0 0 0 0 0 0 0) (vector 0 0 0 0 0 0 0 0 0 0)
(vector 0 0 0 0 0 0 0 0 0 0) (vector 0 0 0 0 0 0 0 0 0 0)))
(team-combs (vector '(0 1) '(0 2) '(0 3) '(1 2) '(1 3) '(2 3)))
(single-tupel)
... |
Ensure the translated Common_Lisp code behaves exactly like the original VB snippet. | Module Module1
Class SymbolType
Public ReadOnly symbol As String
Public ReadOnly precedence As Integer
Public ReadOnly rightAssociative As Boolean
Public Sub New(symbol As String, precedence As Integer, rightAssociative As Boolean)
Me.symbol = symbol
Me.prece... |
(defconstant operators "^*/+-")
(defconstant precedence '(-4 3 3 2 2))
(defun operator-p (op)
"string->integer|nil: Returns operator precedence index or nil if not operator."
(and (= (length op) 1) (position (char op 0) operators)))
(defun has-priority (op2 op1)
"(string,string)->boolean: True if op2 has outpu... |
Generate a Common_Lisp translation of this VB snippet without changing its computational steps. | Imports System, BI = System.Numerics.BigInteger, System.Console
Module Module1
Function isqrt(ByVal x As BI) As BI
Dim t As BI, q As BI = 1, r As BI = 0
While q <= x : q <<= 2 : End While
While q > 1 : q >>= 2 : t = x - r - q : r >>= 1
If t >= 0 Then x = t : r += q
End ... | (ql:quickload :computable-reals :silent t)
(use-package :computable-reals)
(setq *print-prec* 70)
(defparameter *iterations* 52)
(defun !r (n)
(let ((p 1))
(loop for i from 2 to n doing (setq p (*r p i)))
p))
(defun integral (n)
(let* ((polynomial (+r (*r 532 n n) (*r 126 n) 9))
(numer (*r 3... |
Rewrite the snippet below in Common_Lisp so it works the same as the original VB code. | Imports System, BI = System.Numerics.BigInteger, System.Console
Module Module1
Function isqrt(ByVal x As BI) As BI
Dim t As BI, q As BI = 1, r As BI = 0
While q <= x : q <<= 2 : End While
While q > 1 : q >>= 2 : t = x - r - q : r >>= 1
If t >= 0 Then x = t : r += q
End ... | (ql:quickload :computable-reals :silent t)
(use-package :computable-reals)
(setq *print-prec* 70)
(defparameter *iterations* 52)
(defun !r (n)
(let ((p 1))
(loop for i from 2 to n doing (setq p (*r p i)))
p))
(defun integral (n)
(let* ((polynomial (+r (*r 532 n n) (*r 126 n) 9))
(numer (*r 3... |
Generate an equivalent Common_Lisp version of this VB code. | Imports System.Numerics
Public Class BigRat
Implements IComparable
Public nu, de As BigInteger
Public Shared Zero = New BigRat(BigInteger.Zero, BigInteger.One),
One = New BigRat(BigInteger.One, BigInteger.One)
Sub New(bRat As BigRat)
nu = bRat.nu : de = bRat.de
End Sub
... | (ns tanevaulator
(:gen-class))
(def test-cases [
[[1, 1, 2], [1, 1, 3]],
[[2, 1, 3], [1, 1, 7]],
[[4, 1, 5], [-1, 1, 239]],
[[5, 1, 7], [2, 3, 79]],
[[1, 1, 2], [1, 1, 5], [1, 1, 8]],
... |
Change the programming language of this snippet from VB to Common_Lisp without modifying what it does. | Imports System.Numerics
Public Class BigRat
Implements IComparable
Public nu, de As BigInteger
Public Shared Zero = New BigRat(BigInteger.Zero, BigInteger.One),
One = New BigRat(BigInteger.One, BigInteger.One)
Sub New(bRat As BigRat)
nu = bRat.nu : de = bRat.de
End Sub
... | (ns tanevaulator
(:gen-class))
(def test-cases [
[[1, 1, 2], [1, 1, 3]],
[[2, 1, 3], [1, 1, 7]],
[[4, 1, 5], [-1, 1, 239]],
[[5, 1, 7], [2, 3, 79]],
[[1, 1, 2], [1, 1, 5], [1, 1, 8]],
... |
Keep all operations the same but rewrite the snippet in Tcl. | package main
import (
"fmt"
"log"
"math"
"os"
"path/filepath"
)
func commatize(n int64) string {
s := fmt.Sprintf("%d", n)
if n < 0 {
s = s[1:]
}
le := len(s)
for i := le - 3; i >= 1; i -= 3 {
s = s[0:i] + "," + s[i:]
}
if n >= 0 {
return s
}... | package require fileutil::traverse
namespace path {::tcl::mathfunc ::tcl::mathop}
proc ? {test a b} {tailcall if $test [list subst $a] [list subst $b]}
set dir [? {$argc} {[lindex $argv 0]} .]
fileutil::traverse Tobj $dir \
-prefilter {apply {path {ne [file type $path] link}}} \
-filter {apply {path {eq [file t... |
Can you help me rewrite this code in Tcl instead of Go, keeping it the same logically? |
package main
import "fmt"
const (
maxn = 10
maxl = 50
)
func main() {
for i := 1; i <= maxn; i++ {
fmt.Printf("%d: %d\n", i, steps(i))
}
}
func steps(n int) int {
var a, b [maxl][maxn + 1]int
var x [maxl]int
a[0][0] = 1
var m int
for l := 0; ; {
x[l]++
... | package require struct::list
proc swap {listVar} {
upvar 1 $listVar list
set n [lindex $list 0]
for {set i 0; set j [expr {$n-1}]} {$i<$j} {incr i;incr j -1} {
set tmp [lindex $list $i]
lset list $i [lindex $list $j]
lset list $j $tmp
}
}
proc swaps {list} {
for {set i 0} {[lindex $list 0] > 1}... |
Rewrite this program in Tcl while keeping its functionality equivalent to the Go version. | package main
import (
"fmt"
"unicode"
)
const (
lcASCII = "abcdefghijklmnopqrstuvwxyz"
ucASCII = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
)
func main() {
fmt.Println("ASCII lower case:")
fmt.Println(lcASCII)
for l := 'a'; l <= 'z'; l++ {
fmt.Print(string(l))
}
fmt.Println()
fmt.Println("\nASCII upper case:")
fmt.P... | for {set c 0} {$c <= 0xffff} {incr c} {
set ch [format "%c" $c]
if {[string is upper $ch]} {lappend upper $ch}
if {[string is lower $ch]} {lappend lower $ch}
}
puts "Upper: $upper"
puts "Lower: $lower"
|
Generate a Tcl translation of this Go snippet without changing its computational steps. | package main
import (
"fmt"
"sync"
"time"
)
var value int
var m sync.Mutex
var wg sync.WaitGroup
func slowInc() {
m.Lock()
v := value
time.Sleep(1e8)
value = v+1
m.Unlock()
wg.Done()
}
func main() {
wg.Add(2)
go slowInc()
go slowInc()
wg.Wait()
fmt.Println(val... | package require Thread
set m [thread::mutex create]
thread::mutex lock $m
thread::mutex unlock $m
thread::mutex destroy $m
|
Generate a Tcl translation of this Go snippet without changing its computational steps. | package main
import "fmt"
func jaro(str1, str2 string) float64 {
if len(str1) == 0 && len(str2) == 0 {
return 1
}
if len(str1) == 0 || len(str2) == 0 {
return 0
}
match_distance := len(str1)
if len(str2) > match_distance {
match_distance = len(str2)
}
match_dist... | proc jaro {s1 s2} {
set l1 [string length $s1]
set l2 [string length $s2]
set dmax [expr {max($l1, $l2)/2 - 1}] ;
set m1 {} ;
set m2 {}
for {set i 0} {$i < $l1} {incr i} {
set jmin [expr {$i - $dmax}] ;
set jmax [expr {$i + $dmax}] ;
... |
Produce a language-to-language conversion: from Go to Tcl, same semantics. | package main
import (
"bytes"
"fmt"
"io"
"os"
"unicode"
)
func main() {
owp(os.Stdout, bytes.NewBufferString("what,is,the;meaning,of:life."))
fmt.Println()
owp(os.Stdout, bytes.NewBufferString("we,are;not,in,kansas;any,more."))
fmt.Println()
}
func owp(dst io.Writer, src io.Reader... | package require Tcl 8.6
proc fwd c {
expr {[string is alpha $c] ? "[fwd [yield f][puts -nonewline $c]]" : $c}
}
proc rev c {
expr {[string is alpha $c] ? "[rev [yield r]][puts -nonewline $c]" : $c}
}
coroutine f while 1 {puts -nonewline [fwd [yield r]]}
coroutine r while 1 {puts -nonewline [rev [yield f]]}
for... |
Ensure the translated Tcl code behaves exactly like the original Go snippet. | package main
import "fmt"
type rs232p9 uint16
const (
CD9 rs232p9 = 1 << iota
RD9
TD9
DTR9
SG9
DSR9
RTS9
CTS9
RI9
)
func main() {
... | set rs232_bits {CD RD TD DTR SG DSR RTS CTS RI}
proc rs232_encode args {
set res 0
foreach arg $args {
set pos [lsearch $::rs232_bits $arg]
if {$pos >=0} {set res [expr {$res | 1<<$pos}]}
}
return $res
}
proc rs232_decode int {
set res {}
set i -1
foreach bit $::rs232_bits {... |
Convert the following code from Go to Tcl, ensuring the logic remains intact. | package main
import (
"fmt"
"strconv"
)
func main() {
var maxLen int
var seqMaxLen [][]string
for n := 1; n < 1e6; n++ {
switch s := seq(n); {
case len(s) == maxLen:
seqMaxLen = append(seqMaxLen, s)
case len(s) > maxLen:
maxLen = len(s)
s... | proc nextterm n {
foreach c [split $n ""] {incr t($c)}
foreach c {9 8 7 6 5 4 3 2 1 0} {
if {[info exist t($c)]} {append r $t($c) $c}
}
return $r
}
apply {limit {
set done [lrepeat [set l2 [expr {$limit * 100}]] 0]
set maxlen 0
set maxes {}
for {set i 0} {$i < $limit} {incr i... |
Keep all operations the same but rewrite the snippet in Tcl. | package main
import (
"fmt"
"strconv"
"strings"
)
func sdn(n int64) bool {
if n >= 1e10 {
return false
}
s := strconv.FormatInt(n, 10)
for d, p := range s {
if int(p)-'0' != strings.Count(s, strconv.Itoa(d)) {
return false
}
}
return true
}
fu... | package require Tcl 8.5
proc isSelfDescribing num {
set digits [split $num ""]
set len [llength $digits]
set count [lrepeat $len 0]
foreach d $digits {
if {$d >= $len} {return false}
lset count $d [expr {[lindex $count $d] + 1}]
}
foreach d $digits c $count {if {$c != $d} {return false}}
r... |
Ensure the translated Tcl code behaves exactly like the original Go snippet. | package main
import (
"errors"
"fmt"
"os"
)
type dtText struct {
rules, text string
}
var ptText = []dtText{
{"YYYYNNNN", "Printer does not print"},
{"YYNNYYNN", "A red light is flashing"},
{"YNYNYNYN", "Printer is unrecognised"},
{"--------", ""},
{" X ", "Check the power ca... | package require TclOO
proc yesno {{message "Press Y or N to continue"}} {
fconfigure stdin -blocking 0
exec stty raw
read stdin ;
puts -nonewline "${message}: "
flush stdout
while {![eof stdin]} {
set c [string tolower [read stdin 1]]
if {$c eq "y" || $c eq "n"} break
}
... |
Translate this program into Tcl but keep the logic exactly as in Go. | package main
import (
"bufio"
"fmt"
"io"
"log"
"os"
)
func main() {
var lines int
n, err := fmt.Scanln(&lines)
if n != 1 || err != nil {
log.Fatal(err)
}
scanner := bufio.NewScanner(os.Stdin)
scanner.Split(bufio.ScanLines)
for ; scanner.Scan() && lines > 0; lines-- {... | proc do_stuff {line} {
puts $line
}
foreach - [lrepeat [gets stdin] dummy] {
do_stuff [gets stdin]
}
|
Can you help me rewrite this code in Tcl instead of Go, keeping it the same logically? | package main
import (
"bytes"
"fmt"
"io/ioutil"
"log"
"strings"
"unicode/utf8"
)
func main() {
wordList := "unixdict.txt"
b, err := ioutil.ReadFile(wordList)
if err != nil {
log.Fatal("Error reading file")
}
bwords := bytes.Fields(b)
var words []string
for _... | foreach w [read [open unixdict.txt]] {
if {[string first the $w] != -1 && [string length $w] > 11} {
puts $w
}
}
|
Convert this Go snippet to Tcl and keep its semantics consistent. | package avl
type Key interface {
Less(Key) bool
Eq(Key) bool
}
type Node struct {
Data Key
Balance int
Link [2]*Node
}
func opp(dir int) int {
return 1 - dir
}
func single(root *Node, dir int) *Node {
save := root.Link[opp(dir)]
root.Link[opp(dir)] = save... | package require TclOO
namespace eval AVL {
oo::class create Tree {
variable root nil class
constructor {{nodeClass AVL::Node}} {
set class [oo::class create Node [list superclass $nodeClass]]
set nil [my NewNode ""]
set root [$nil ref]
oo::objdefine $nil {
method height ... |
Rewrite this program in Tcl while keeping its functionality equivalent to the Go version. | package avl
type Key interface {
Less(Key) bool
Eq(Key) bool
}
type Node struct {
Data Key
Balance int
Link [2]*Node
}
func opp(dir int) int {
return 1 - dir
}
func single(root *Node, dir int) *Node {
save := root.Link[opp(dir)]
root.Link[opp(dir)] = save... | package require TclOO
namespace eval AVL {
oo::class create Tree {
variable root nil class
constructor {{nodeClass AVL::Node}} {
set class [oo::class create Node [list superclass $nodeClass]]
set nil [my NewNode ""]
set root [$nil ref]
oo::objdefine $nil {
method height ... |
Ensure the translated Tcl code behaves exactly like the original Go snippet. | package cf
type NG4 struct {
A1, A int64
B1, B int64
}
func (ng NG4) needsIngest() bool {
if ng.isDone() {
panic("b₁==b==0")
}
return ng.B1 == 0 || ng.B == 0 || ng.A1/ng.B1 != ng.A/ng.B
}
func (ng NG4) isDone() bool {
return ng.B1 == 0 && ng.B == 0
}
func (ng *NG4) ingest(t int64) {
... |
oo::class create NG1 {
superclass Generator
variable a1 a b1 b cf
constructor args {
next
lassign $args a1 a b1 b
}
method Ingress n {
lassign [list [expr {$a + $a1*$n}] $a1 [expr {$b + $b1*$n}] $b1] \
a1 a b1 b
}
method NeedTerm? {} {
expr {$b1 == 0 || $b == 0 || $a/$b != $a1/$b1... |
Transform the following Go implementation into Tcl, maintaining the same output and logic. | package cf
type NG4 struct {
A1, A int64
B1, B int64
}
func (ng NG4) needsIngest() bool {
if ng.isDone() {
panic("b₁==b==0")
}
return ng.B1 == 0 || ng.B == 0 || ng.A1/ng.B1 != ng.A/ng.B
}
func (ng NG4) isDone() bool {
return ng.B1 == 0 && ng.B == 0
}
func (ng *NG4) ingest(t int64) {
... |
oo::class create NG1 {
superclass Generator
variable a1 a b1 b cf
constructor args {
next
lassign $args a1 a b1 b
}
method Ingress n {
lassign [list [expr {$a + $a1*$n}] $a1 [expr {$b + $b1*$n}] $b1] \
a1 a b1 b
}
method NeedTerm? {} {
expr {$b1 == 0 || $b == 0 || $a/$b != $a1/$b1... |
Write the same code in Tcl as shown below in Go. | var m = ` leading spaces
and blank lines`
| set hereDocExample {
In Tcl, the {curly brace} notation is strictly a here-document style notation
as it permits arbitrary content inside it *except* for an unbalanced brace.
That is typically not a problem as seen in reality, as almost all content that
might be placed in a here-doc is either brace-free or balanced.
T... |
Convert this Go block to Tcl, preserving its control flow and logic. | var m = ` leading spaces
and blank lines`
| set hereDocExample {
In Tcl, the {curly brace} notation is strictly a here-document style notation
as it permits arbitrary content inside it *except* for an unbalanced brace.
That is typically not a problem as seen in reality, as almost all content that
might be placed in a here-doc is either brace-free or balanced.
T... |
Please provide an equivalent version of this Go code in Tcl. | package main
import (
"fmt"
"unsafe"
)
func main() {
myVar := 3.14
myPointer := &myVar
fmt.Println("Address:", myPointer, &myVar)
fmt.Printf("Address: %p %p\n", myPointer, &myVar)
var addr64 int64
var addr32 int32
ptr := unsafe.Pointer(myPointer)
if unsafe.Sizeof(ptr) <= unsafe.Sizeof(addr64) {
addr64 = ... | package require critcl
critcl::cproc peek {int addr} int {
union {
int i;
int *a;
} u;
u.i = addr;
return *u.a;
}
critcl::cproc poke {int addr int value} void {
union {
int i;
int *a;
} u;
u.i = addr;
*u.a = value;
}
package provide poker 1.0
|
Transform the following Go implementation into Tcl, maintaining the same output and logic. | package main
import (
"bufio"
"fmt"
"log"
"math/rand"
"os"
"os/exec"
"strconv"
"strings"
"text/template"
"time"
"unicode"
"golang.org/x/crypto/ssh/terminal"
)
const maxPoints = 2048
const (
fieldSizeX = 4
fieldSizeY = 4
)
const tilesAtStart = 2
const probFor2 = 0.9
type button int
const (
_ button =... |
package require Tcl 8.5
package require struct::matrix
package require struct::list
set size 4
proc forcells {cellList varName1 varName2 cellVarName script} {
upvar $varName1 i
upvar $varName2 j
upvar $cellVarName c
foreach cell $cellList {
set i [lindex $cell 0]
set... |
Keep all operations the same but rewrite the snippet in Tcl. | package pig
import (
"fmt"
"math/rand"
"time"
)
type (
PlayerID int
MessageID int
StrategyID int
PigGameData struct {
player PlayerID
turnCount int
turnRollCount int
turnScore int
lastRoll int
scores [2]int
verbose bool
}
)
const (
gameOver = iota
pigged... | package require TclOO
oo::class create Player {
variable me
constructor {name} {
set me $name
}
method name {} {
return $me
}
method wantToRoll {safeScore roundScore} {}
method rolled {who what} {
if {$who ne [self]} {
}
}
method turnend {who score} {
if {$who ne [self]... |
Port the following code from Go to Tcl with equivalent syntax and logic. | package pig
import (
"fmt"
"math/rand"
"time"
)
type (
PlayerID int
MessageID int
StrategyID int
PigGameData struct {
player PlayerID
turnCount int
turnRollCount int
turnScore int
lastRoll int
scores [2]int
verbose bool
}
)
const (
gameOver = iota
pigged... | package require TclOO
oo::class create Player {
variable me
constructor {name} {
set me $name
}
method name {} {
return $me
}
method wantToRoll {safeScore roundScore} {}
method rolled {who what} {
if {$who ne [self]} {
}
}
method turnend {who score} {
if {$who ne [self]... |
Port the following code from Go to Tcl with equivalent syntax and logic. | package main
import (
"fmt"
"log"
"os"
"os/exec"
)
func reverseBytes(bytes []byte) {
for i, j := 0, len(bytes)-1; i < j; i, j = i+1, j-1 {
bytes[i], bytes[j] = bytes[j], bytes[i]
}
}
func check(err error) {
if err != nil {
log.Fatal(err)
}
}
func main() {
in, err ... | chan configure stdin -translation binary
chan configure stdout -translation binary
set lines [regexp -inline -all {.{80}} [read stdin]]
puts -nonewline [join [lmap line $lines {string reverse $line}] ""]
|
Transform the following Go implementation into Tcl, maintaining the same output and logic. | package main
import (
"bytes"
"fmt"
"math/rand"
"time"
)
type maze struct {
c2 [][]byte
h2 [][]byte
v2 [][]byte
}
func newMaze(rows, cols int) *maze {
c := make([]byte, rows*cols)
h := bytes.Repeat([]byte{'-'}, rows*cols)
v := bytes.Repeat([]byte{'|'}, rows... | oo::define maze {
method solve {} {
set visited [lrepeat $x [lrepeat $y 0]]
set queue {0 0 {}}
while 1 {
if {[llength $queue] == 0} {
error "cannot reach finish"
}
set queue [lassign $queue cx cy path]
if {[lindex $visited $cx $cy]} continue
lset visited $cx $cy 1
... |
Convert this Go block to Tcl, preserving its control flow and logic. | package main
import (
"fmt"
"math"
)
type rule func(float64, float64) float64
var dxs = []float64{
-0.533, 0.270, 0.859, -0.043, -0.205, -0.127, -0.071, 0.275,
1.251, -0.231, -0.401, 0.269, 0.491, 0.951, 1.150, 0.001,
-0.382, 0.161, 0.915, 2.080, -2.337, 0.034, -0.126, 0.014,
0... | package require Tcl 8.6
namespace path {tcl::mathop tcl::mathfunc}
proc funnel {items rule} {
set x 0.0
set result {}
foreach item $items {
lappend result [+ $x $item]
set x [apply $rule $x $item]
}
return $result
}
proc mean {items} {
/ [+ {*}$items] [double [llength $items]]
}
proc stddev ... |
Convert this Go snippet to Tcl and keep its semantics consistent. | package main
import (
"fmt"
"math"
)
type rule func(float64, float64) float64
var dxs = []float64{
-0.533, 0.270, 0.859, -0.043, -0.205, -0.127, -0.071, 0.275,
1.251, -0.231, -0.401, 0.269, 0.491, 0.951, 1.150, 0.001,
-0.382, 0.161, 0.915, 2.080, -2.337, 0.034, -0.126, 0.014,
0... | package require Tcl 8.6
namespace path {tcl::mathop tcl::mathfunc}
proc funnel {items rule} {
set x 0.0
set result {}
foreach item $items {
lappend result [+ $x $item]
set x [apply $rule $x $item]
}
return $result
}
proc mean {items} {
/ [+ {*}$items] [double [llength $items]]
}
proc stddev ... |
Change the programming language of this snippet from Go to Tcl without modifying what it does. | package main
import "fmt"
func main() {
for {
fmt.Printf("SPAM\n")
}
}
| while true {
puts SPAM
}
for {} 1 {} {
puts SPAM
}
|
Port the following code from Go to Tcl with equivalent syntax and logic. | func assert(t bool, s string) {
if !t {
panic(s)
}
}
assert(c == 0, "some text here")
|
proc require {expression message args} {
if {![uplevel 1 [list expr $expression]]} {
set msg [uplevel 1 [list format $message] $args]
return -level 2 -code error "PRECONDITION FAILED: $msg"
}
}
proc ensure {expression {message ""} args} {
if {![uplevel 1 [list expr $expression]]} {
set msg [uplevel 1 [l... |
Convert this Go snippet to Tcl and keep its semantics consistent. | func assert(t bool, s string) {
if !t {
panic(s)
}
}
assert(c == 0, "some text here")
|
proc require {expression message args} {
if {![uplevel 1 [list expr $expression]]} {
set msg [uplevel 1 [list format $message] $args]
return -level 2 -code error "PRECONDITION FAILED: $msg"
}
}
proc ensure {expression {message ""} args} {
if {![uplevel 1 [list expr $expression]]} {
set msg [uplevel 1 [l... |
Generate an equivalent Tcl version of this Go code. | package main
import (
"fmt"
"runtime"
"sync"
)
func main() {
p := sync.Pool{New: func() interface{} {
fmt.Println("pool empty")
return new(int)
}}
i := new(int)
j := new(int)
*i = 1
*j = 2
fmt.Println(*i + *j)
p.P... | package require Tcl 8.6
oo::class create Pool {
superclass oo::class
variable capacity pool busy
unexport create
constructor args {
next {*}$args
set capacity 100
set pool [set busy {}]
}
method new {args} {
if {[llength $pool]} {
set pool [lassign $pool obj]
} else {
if {[llength... |
Generate a Tcl translation of this Go snippet without changing its computational steps. | package main
import (
"fmt"
"runtime"
"sync"
)
func main() {
p := sync.Pool{New: func() interface{} {
fmt.Println("pool empty")
return new(int)
}}
i := new(int)
j := new(int)
*i = 1
*j = 2
fmt.Println(*i + *j)
p.P... | package require Tcl 8.6
oo::class create Pool {
superclass oo::class
variable capacity pool busy
unexport create
constructor args {
next {*}$args
set capacity 100
set pool [set busy {}]
}
method new {args} {
if {[llength $pool]} {
set pool [lassign $pool obj]
} else {
if {[llength... |
Rewrite the snippet below in Tcl so it works the same as the original Go code. | package main
import (
"fmt"
"sort"
"sync"
"time"
)
type history struct {
timestamp tsFunc
hs []hset
}
type tsFunc func() time.Time
type hset struct {
int
t time.Time
}
func newHistory(ts tsFunc) history {
return history{ts, []hset{{t: ts()}}}
}
... |
proc histvar {varName operation} {
upvar 1 $varName v ___history($varName) history
switch -- $operation {
start {
set history {}
if {[info exist v]} {
lappend history $v
}
trace add variable v write [list histvar.write $varName]
trace add variable v read [list histvar.read $varName]... |
Change the programming language of this snippet from Go to Tcl without modifying what it does. | package main
import (
"github.com/fogleman/gg"
"log"
"os/exec"
"runtime"
)
var palette = [8]string{
"000000",
"FF0000",
"00FF00",
"0000FF",
"FF00FF",
"00FFFF",
"FFFF00",
"FFFFFF",
}
func pinstripe(dc *gg.Context) {
w := dc.Width()
h := dc.Height() / 7... | package require Tk
canvas .c
set colors {black red green blue magenta cyan yellow white}
for {set y 0;set dx 1} {$y < 11*72} {incr y 72;incr dx} {
for {set x 0;set c 0} {$x < 8.5*72} {incr x $dx;incr c} {
.c create rectangle $x $y [expr {$x+$dx+1}] [expr {$y+73}] \
-fill [lindex $colors [expr {$c%[llength ... |
Write the same algorithm in Tcl as shown in this Go implementation. | func multiply(a, b float64) float64 {
return a * b
}
| proc multiply { arg1 arg2 } {
return [expr {$arg1 * $arg2}]
}
|
Write the same code in Tcl as shown below in Go. | package main
import (
"fmt"
"os"
"golang.org/x/crypto/ssh/terminal"
)
func main() {
w, h, err := terminal.GetSize(int(os.Stdout.Fd()))
if err != nil {
fmt.Println(err)
return
}
fmt.Println(h, w)
}
| set width [exec tput cols]
set height [exec tput lines]
puts "The terminal is $width characters wide and has $height lines"
|
Convert this Go block to Tcl, preserving its control flow and logic. | package main
import (
"fmt"
"permute"
)
func determinant(m [][]float64) (d float64) {
p := make([]int, len(m))
for i := range p {
p[i] = i
}
it := permute.Iter(p)
for s := it(); s != 0; s = it() {
pr := 1.
for i, σ := range p {
pr *= m[i][σ]
}
... | package require math::linearalgebra
package require struct::list
proc permanent {matrix} {
for {set plist {};set i 0} {$i<[llength $matrix]} {incr i} {
lappend plist $i
}
foreach p [::struct::list permutations $plist] {
foreach i $plist j $p {
lappend prod [lindex $matrix $i $j]
}
lappend sum [::t... |
Change the programming language of this snippet from Go to Tcl without modifying what it does. | package main
import (
"fmt"
"permute"
)
func determinant(m [][]float64) (d float64) {
p := make([]int, len(m))
for i := range p {
p[i] = i
}
it := permute.Iter(p)
for s := it(); s != 0; s = it() {
pr := 1.
for i, σ := range p {
pr *= m[i][σ]
}
... | package require math::linearalgebra
package require struct::list
proc permanent {matrix} {
for {set plist {};set i 0} {$i<[llength $matrix]} {incr i} {
lappend plist $i
}
foreach p [::struct::list permutations $plist] {
foreach i $plist j $p {
lappend prod [lindex $matrix $i $j]
}
lappend sum [::t... |
Convert the following code from Go to Tcl, ensuring the logic remains intact. | package main
import (
"fmt"
"io"
"log"
"os"
"github.com/stacktic/ftp"
)
func main() {
const (
hostport = "localhost:21"
username = "anonymous"
password = "anonymous"
dir = "pub"
file = "somefile.bin"
)
conn, err := ftp.Connect(hostport)
if err != nil {
log.Fatal(err)
}
defer conn.Q... | package require ftp
set conn [::ftp::Open kernel.org anonymous "" -mode passive]
::ftp::Cd $conn /pub/linux/kernel
foreach line [ftp::NList $conn] {
puts $line
}
::ftp::Type $conn binary
::ftp::Get $conn README README
|
Produce a functionally identical Tcl code for the snippet given in Go. | package main
import (
"database/sql"
"fmt"
"log"
_ "github.com/mattn/go-sqlite3"
)
func main() {
db, err := sql.Open("sqlite3", "rc.db")
if err != nil {
log.Print(err)
return
}
defer db.Close()
_, err = db.Exec(`create table addr (
id int uniq... | package require sqlite3
sqlite3 db address.db
db eval {
CREATE TABLE address (
addrID INTEGER PRIMARY KEY AUTOINCREMENT,
addrStreet TEXT NOT NULL,
addrCity TEXT NOT NULL,
addrState TEXT NOT NULL,
addrZIP TEXT NOT NULL
)
}
|
Generate a Tcl translation of this Go snippet without changing its computational steps. | package main
import (
"fmt"
"math/rand"
"time"
)
func cyclesort(ints []int) int {
writes := 0
for cyclestart := 0; cyclestart < len(ints)-1; cyclestart++ {
item := ints[cyclestart]
pos := cyclestart
for i := cyclestart + 1; i < len(ints); i++ {
if ints[i] < item {
pos++
}
}
if pos == cycl... | proc cycleSort {listVar} {
upvar 1 $listVar array
set writes 0
for {set cycleStart 0} {$cycleStart < [llength $array]} {incr cycleStart} {
set item [lindex $array $cycleStart]
set pos $cycleStart
for {set i [expr {$pos + 1}]} {$i < [llength $array]} {incr i} {
incr pos [expr {[lindex $arra... |
Rewrite this program in Tcl while keeping its functionality equivalent to the Go version. | package main
import (
"fmt"
"math/rand"
"time"
)
func cyclesort(ints []int) int {
writes := 0
for cyclestart := 0; cyclestart < len(ints)-1; cyclestart++ {
item := ints[cyclestart]
pos := cyclestart
for i := cyclestart + 1; i < len(ints); i++ {
if ints[i] < item {
pos++
}
}
if pos == cycl... | proc cycleSort {listVar} {
upvar 1 $listVar array
set writes 0
for {set cycleStart 0} {$cycleStart < [llength $array]} {incr cycleStart} {
set item [lindex $array $cycleStart]
set pos $cycleStart
for {set i [expr {$pos + 1}]} {$i < [llength $array]} {incr i} {
incr pos [expr {[lindex $arra... |
Please provide an equivalent version of this Go code in Tcl. | package main
import (
"archive/tar"
"compress/gzip"
"flag"
"io"
"log"
"os"
"time"
)
func main() {
filename := flag.String("file", "TAPE.FILE", "filename within TAR")
data := flag.String("data", "", "data for file")
outfile := flag.String(... | cd /tmp
set f [open hello.jnk w]
puts $f "Hello World!"
close $f
set fin [open "|tar cf - hello.jnk" rb]
set fout [open /dev/tape wb]
fcopy $fin $fout
close $fin
close $fout
|
Convert this Go block to Tcl, preserving its control flow and logic. | package main
import (
"fmt"
"github.com/jbarham/primegen"
"math"
"math/big"
"math/rand"
"sort"
"time"
)
const (
maxCurves = 10000
maxRnd = 1 << 31
maxB1 = uint64(43 * 1e7)
maxB2 = uint64(2 * 1e10)
)
var (
zero = big.NewInt(0)
one = big.NewInt(1)
t... | namespace import ::tcl::mathop::*
package require math::numtheory 1.1.1;
proc fermat n {
+ [** 2 [** 2 $n]] 1
}
for {set i 0} {$i < 10} {incr i} {
puts "F$i = [fermat $i]"
}
for {set i 1} {1} {incr i} {
puts -nonewline "F$i... "
flush stdout
set F [fermat $i]
set factors [math::numtheory::primeFactors $F]
i... |
Change the programming language of this snippet from Go to Tcl without modifying what it does. | package main
import (
"fmt"
"sync"
)
var a = []int{170, 45, 75, 90, 802, 24, 2, 66}
var aMax = 1000
const bead = 'o'
func main() {
fmt.Println("before:", a)
beadSort()
fmt.Println("after: ", a)
}
func beadSort() {
all := make([]byte, aMax*len(a))
abacus := make([][]byte, ... | package require Tcl 8.5
proc beadsort numList {
if {![llength $numList]} return
foreach n $numList {
for {set i 0} {$i<$n} {incr i} {
dict incr vals $i
}
}
foreach n [dict values $vals] {
for {set i 0} {$i<$n} {incr i} {
dict incr result $i
}
}
dict values $res... |
Write the same code in Tcl as shown below in Go. | package main
import (
"fmt"
"log"
"strconv"
)
func co9Peterson(base int) (cob func(string) (byte, error), err error) {
if base < 2 || base > 36 {
return nil, fmt.Errorf("co9Peterson: %d invalid base", base)
}
addDigits := func(a, b byte) (string, error) {... | proc co9 {x} {
while {[string length $x] > 1} {
set x [tcl::mathop::+ {*}[split $x ""]]
}
return $x
}
proc coBase {x {base 10}} {
while {$x >= $base} {
for {set digits {}} {$x} {set x [expr {$x / $base}]} {
lappend digits [expr {$x % $base}]
}
set x [tcl::mathop::+ {*}$digits]
}
return... |
Port the following code from Go to Tcl with equivalent syntax and logic. | package main
import (
"fmt"
"log"
"strconv"
)
func co9Peterson(base int) (cob func(string) (byte, error), err error) {
if base < 2 || base > 36 {
return nil, fmt.Errorf("co9Peterson: %d invalid base", base)
}
addDigits := func(a, b byte) (string, error) {... | proc co9 {x} {
while {[string length $x] > 1} {
set x [tcl::mathop::+ {*}[split $x ""]]
}
return $x
}
proc coBase {x {base 10}} {
while {$x >= $base} {
for {set digits {}} {$x} {set x [expr {$x / $base}]} {
lappend digits [expr {$x % $base}]
}
set x [tcl::mathop::+ {*}$digits]
}
return... |
Transform the following Go implementation into Tcl, maintaining the same output and logic. | package main
import (
"encoding/json"
"fmt"
"io"
"os"
"sort"
"strings"
"time"
"unicode"
)
type Item struct {
Stamp time.Time
Name string
Tags []string `json:",omitempty"`
Notes string `json:",omitempty"`
}
func (i *Item) String() string {
s := i.Stamp.Format... |
package require Tcl 8.6
namespace eval udb {
variable db {}
proc Load {filename} {
variable db
if {[catch {set f [open $filename]}]} {
set db {}
return
}
set db [read $f]
close $f
}
proc Store {filename} {
variable db
if {[catch {set f [open $filename w]}]} return
dict for {nm inf} $... |
Transform the following Go implementation into Tcl, maintaining the same output and logic. | package main
import "C"
import "fmt"
import "unsafe"
func main() {
d := C.XOpenDisplay(nil)
f7, f6 := C.CString("F7"), C.CString("F6")
defer C.free(unsafe.Pointer(f7))
defer C.free(unsafe.Pointer(f6))
if d != nil {
C.XGrabKey(d, C.int(C.XKeysymToKeycode(d, C.XStringToKeysym(f7))),
... | package require Tk
pack [label .l -text "C-x C-s to save, C-x C-c to quit"]
focus .
bind . <Control-x><Control-s> {
tk_messageBox -message "We would save here"
}
bind . <Control-x><Control-c> {exit}
|
Maintain the same structure and functionality when rewriting this code in Tcl. | package cards
import (
"math/rand"
)
type Suit uint8
const (
Spade Suit = 3
Heart Suit = 2
Diamond Suit = 1
Club Suit = 0
)
func (s Suit) String() string {
const suites = "CDHS"
return suites[s : s+1]
}
type Rank uint8
const (
Ace Rank = 1
Two Rank = 2
Three Rank = 3
Four Rank = 4
Fiv... | package require Tcl 8.5
namespace eval playing_cards {
variable deck
variable suits {\u2663 \u2662 \u2661 \u2660}
variable pips {2 3 4 5 6 7 8 9 10 J Q K A}
proc new_deck {} {
variable deck
set deck [list]
for {set i 0} {$i < 52} {incr i} {
lappend deck $i
... |
Write the same algorithm in Tcl as shown in this Go implementation. | package main
import "fmt"
func gcd(n, k int) int {
if n < k || k < 1 {
panic("Need n >= k and k >= 1")
}
s := 1
for n&1 == 0 && k&1 == 0 {
n >>= 1
k >>= 1
s <<= 1
}
t := n
if n&1 != 0 {
t = -k
}
for t != 0 {
for t&1 == 0 {
... | array set cache {}
set cache(0) 0
proc gcd {i j} {
while {$j != 0} {
set t [expr {$i % $j}]
set i $j
set j $t
}
return $i
}
proc is_perfect_totient {n} {
global cache
set tot 0
for {set i 1} {$i < $n} {incr i} {
if [ expr [gcd $i $n] == 1 ] {
incr tot
... |
Port the provided Go code into Tcl while preserving the original functionality. | package main
import "fmt"
func gcd(n, k int) int {
if n < k || k < 1 {
panic("Need n >= k and k >= 1")
}
s := 1
for n&1 == 0 && k&1 == 0 {
n >>= 1
k >>= 1
s <<= 1
}
t := n
if n&1 != 0 {
t = -k
}
for t != 0 {
for t&1 == 0 {
... | array set cache {}
set cache(0) 0
proc gcd {i j} {
while {$j != 0} {
set t [expr {$i % $j}]
set i $j
set j $t
}
return $i
}
proc is_perfect_totient {n} {
global cache
set tot 0
for {set i 1} {$i < $n} {incr i} {
if [ expr [gcd $i $n] == 1 ] {
incr tot
... |
Change the programming language of this snippet from Go to Tcl without modifying what it does. | package main
import (
"fmt"
"math/big"
)
func main() {
limit := 100
last := 12
unsigned := true
l := make([][]*big.Int, limit+1)
for n := 0; n <= limit; n++ {
l[n] = make([]*big.Int, limit+1)
for k := 0; k <= limit; k++ {
l[n][k] = new(big.Int)
}
... | proc prod {from to} {
set r 1
if {$from <= $to} {
set r $from
while {[incr from] <= $to} {
set r [expr {$r * $from}]
}
}
return $r
}
proc US3 {n k} {
if {$n < 0 || $k < 0} {
error "US3(): negative arg ($n,$k)"
}
if {$n == ... |
Keep all operations the same but rewrite the snippet in Tcl. | package main
import (
"fmt"
"math/big"
)
func main() {
limit := 100
last := 12
unsigned := true
l := make([][]*big.Int, limit+1)
for n := 0; n <= limit; n++ {
l[n] = make([]*big.Int, limit+1)
for k := 0; k <= limit; k++ {
l[n][k] = new(big.Int)
}
... | proc prod {from to} {
set r 1
if {$from <= $to} {
set r $from
while {[incr from] <= $to} {
set r [expr {$r * $from}]
}
}
return $r
}
proc US3 {n k} {
if {$n < 0 || $k < 0} {
error "US3(): negative arg ($n,$k)"
}
if {$n == ... |
Write the same algorithm in Tcl as shown in this Go implementation. | package main
import (
"fmt"
"os"
"strings"
)
func main() {
lang := strings.ToUpper(os.Getenv("LANG"))
if strings.Contains(lang, "UTF") {
fmt.Printf("This terminal supports unicode and U+25b3 is : %c\n", '\u25b3')
} else {
fmt.Println("This terminal does not support unicode")
... |
if {[string match utf-* [encoding system]] || [string match *unicode* [encoding system]]} {
puts "\u25b3"
} else {
error "terminal does not support unicode (probably)"
}
|
Produce a functionally identical Tcl code for the snippet given in Go. | package main
import (
"fmt"
"os"
"strings"
)
func main() {
lang := strings.ToUpper(os.Getenv("LANG"))
if strings.Contains(lang, "UTF") {
fmt.Printf("This terminal supports unicode and U+25b3 is : %c\n", '\u25b3')
} else {
fmt.Println("This terminal does not support unicode")
... |
if {[string match utf-* [encoding system]] || [string match *unicode* [encoding system]]} {
puts "\u25b3"
} else {
error "terminal does not support unicode (probably)"
}
|
Ensure the translated Tcl code behaves exactly like the original Go snippet. | package main
import (
"fmt"
big "github.com/ncw/gmp"
"time"
)
func sieve(limit int) []bool {
limit++
c := make([]bool, limit)
c[0] = true
c[1] = true
p := 3
for {
p2 := p * p
if p2 >= limit {
break
}
for i := p2; i < limit; i... | package require Tcl 8.5
package require math::numtheory
namespace path ::tcl::mathop
puts [lmap x [math::numtheory::primesLowerThan 5000] {
if {[+ {*}[split $x {}]] == 25} {set x} else continue
}]
|
Port the provided Go code into Tcl while preserving the original functionality. | package main
import (
"fmt"
big "github.com/ncw/gmp"
"time"
)
func sieve(limit int) []bool {
limit++
c := make([]bool, limit)
c[0] = true
c[1] = true
p := 3
for {
p2 := p * p
if p2 >= limit {
break
}
for i := p2; i < limit; i... | package require Tcl 8.5
package require math::numtheory
namespace path ::tcl::mathop
puts [lmap x [math::numtheory::primesLowerThan 5000] {
if {[+ {*}[split $x {}]] == 25} {set x} else continue
}]
|
Please provide an equivalent version of this Go code in Tcl. | package main
import (
"fmt"
"sort"
"strconv"
)
func combrep(n int, lst []byte) [][]byte {
if n == 0 {
return [][]byte{nil}
}
if len(lst) == 0 {
return nil
}
r := combrep(n, lst[1:])
for _, x := range combrep(n-1, lst) {
r = append(r, append(x, lst[0]))
}... | set res {}
set src [list {} 13]
while {[llength $src]} {
set src [lassign $src n r]
foreach d {2 3 5 7} {
if {$d >= $r} {
if {$d == $r} {lappend res "$n$d"}
break
}
lappend src "$n$d" [expr {$r - $d}]
}
}
puts $res
|
Port the provided Go code into Tcl while preserving the original functionality. | package main
import (
"fmt"
"sort"
"strconv"
)
func combrep(n int, lst []byte) [][]byte {
if n == 0 {
return [][]byte{nil}
}
if len(lst) == 0 {
return nil
}
r := combrep(n, lst[1:])
for _, x := range combrep(n-1, lst) {
r = append(r, append(x, lst[0]))
}... | set res {}
set src [list {} 13]
while {[llength $src]} {
set src [lassign $src n r]
foreach d {2 3 5 7} {
if {$d >= $r} {
if {$d == $r} {lappend res "$n$d"}
break
}
lappend src "$n$d" [expr {$r - $d}]
}
}
puts $res
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.