Instruction stringlengths 45 106 | input_code stringlengths 1 13.7k | output_code stringlengths 1 13.7k |
|---|---|---|
Convert the following code from Python to OCaml, ensuring the logic remains intact. | from itertools import permutations
in_order = lambda s: all(x <= s[i+1] for i,x in enumerate(s[:-1]))
perm_sort = lambda s: (p for p in permutations(s) if in_order(p)).next()
| let rec sorted = function
| e1 :: e2 :: r -> e1 <= e2 && sorted (e2 :: r)
| _ -> true
let rec insert e = function
| [] -> [[e]]
| h :: t as l -> (e :: l) :: List.map (fun t' -> h :: t') (insert e t)
let permute xs = List.fold_right (fun h z -> List.concat (List.map (insert h) z))
... |
Translate this program into OCaml but keep the logic exactly as in Python. |
def meaning_of_life():
return 42
if __name__ == "__main__":
print("Main: The meaning of life is %s" % meaning_of_life())
| let meaning_of_life = 42
let main () =
Printf.printf "Main: The meaning of life is %d\n"
meaning_of_life
let () =
if not !Sys.interactive then
main ()
|
Write the same algorithm in OCaml as shown in this Python implementation. |
def meaning_of_life():
return 42
if __name__ == "__main__":
print("Main: The meaning of life is %s" % meaning_of_life())
| let meaning_of_life = 42
let main () =
Printf.printf "Main: The meaning of life is %d\n"
meaning_of_life
let () =
if not !Sys.interactive then
main ()
|
Translate the given Python code snippet into OCaml without altering its behavior. | nicePrimes( s, e ) = { local( m );
forprime( p = s, e,
m = p; \\
while( m > 9, \\ m == p mod 9
m = sumdigits( m ) ); \\
if( isprime( m ),
print1( p, " " ) ) );
}
| let is_nice_prime n =
let rec test x =
x * x > n || n mod x <> 0 && n mod (x + 2) <> 0 && test (x + 6)
in
if n < 5
then n lor 1 = 3
else n land 1 <> 0 && n mod 3 <> 0 && (n + 6) mod 9 land 1 = 0 && test 5
let () =
Seq.(ints 500 |> take 500 |> filter is_nice_prime |> iter (Printf.printf " %u"))
|> pri... |
Convert this Python block to OCaml, preserving its control flow and logic. | nicePrimes( s, e ) = { local( m );
forprime( p = s, e,
m = p; \\
while( m > 9, \\ m == p mod 9
m = sumdigits( m ) ); \\
if( isprime( m ),
print1( p, " " ) ) );
}
| let is_nice_prime n =
let rec test x =
x * x > n || n mod x <> 0 && n mod (x + 2) <> 0 && test (x + 6)
in
if n < 5
then n lor 1 = 3
else n land 1 <> 0 && n mod 3 <> 0 && (n + 6) mod 9 land 1 = 0 && test 5
let () =
Seq.(ints 500 |> take 500 |> filter is_nice_prime |> iter (Printf.printf " %u"))
|> pri... |
Generate a OCaml translation of this Python snippet without changing its computational steps. | import sys
import calendar
year = 2013
if len(sys.argv) > 1:
try:
year = int(sys.argv[-1])
except ValueError:
pass
for month in range(1, 13):
last_sunday = max(week[-1] for week in calendar.monthcalendar(year, month))
print('{}-{}-{:2}'.format(year, calendar.month_abbr[month], last_sun... | let is_leap_year y =
if (y mod 100) = 0
then (y mod 400) = 0
else (y mod 4) = 0;;
let get_days y =
if is_leap_year y
then
[31;29;31;30;31;30;31;31;30;31;30;31]
else
[31;28;31;30;31;30;31;31;30;31;30;31];;
let print_date = Printf.printf "%d/%d/%d\n";;
let get_day_of_week y m d =
... |
Convert this Python snippet to OCaml and keep its semantics consistent. | import sys
import calendar
year = 2013
if len(sys.argv) > 1:
try:
year = int(sys.argv[-1])
except ValueError:
pass
for month in range(1, 13):
last_sunday = max(week[-1] for week in calendar.monthcalendar(year, month))
print('{}-{}-{:2}'.format(year, calendar.month_abbr[month], last_sun... | let is_leap_year y =
if (y mod 100) = 0
then (y mod 400) = 0
else (y mod 4) = 0;;
let get_days y =
if is_leap_year y
then
[31;29;31;30;31;30;31;31;30;31;30;31]
else
[31;28;31;30;31;30;31;31;30;31;30;31];;
let print_date = Printf.printf "%d/%d/%d\n";;
let get_day_of_week y m d =
... |
Convert the following code from Python to OCaml, ensuring the logic remains intact. | import random
random.seed()
attributes_total = 0
count = 0
while attributes_total < 75 or count < 2:
attributes = []
for attribute in range(0, 6):
rolls = []
for roll in range(0, 4):
result = random.randint(1, 6)
rolls.append(result)
sorted_rol... |
let rand_die () : int = Random.int 6
let rand_attr () : int =
let four_rolls = [rand_die (); rand_die (); rand_die (); rand_die ()]
|> List.sort compare in
let three_best = List.tl four_rolls in
List.fold_left (+) 0 three_best
let rand_set () : int list=
[rand_attr (); rand_attr (); rand_attr ();
ra... |
Convert this Python snippet to OCaml and keep its semantics consistent. |
bar = '▁▂▃▄▅▆▇█'
barcount = len(bar)
def sparkline(numbers):
mn, mx = min(numbers), max(numbers)
extent = mx - mn
sparkline = ''.join(bar[min([barcount - 1,
int((n - mn) / extent * barcount)])]
for n in numbers)
return mn, mx, sparkline
if __... | let before_first_bar = 0x2580
let num_bars = 8
let sparkline numbers =
let max_num = List.fold_left max 0. numbers in
let scale = float_of_int num_bars /. max_num in
let bars = Buffer.create num_bars in
let add_bar number =
let scaled = scale *. number |> Float.round |> int_of_float in
if scaled <= 0 t... |
Rewrite the snippet below in OCaml so it works the same as the original Python code. | def longest_increasing_subsequence(X):
N = len(X)
P = [0] * N
M = [0] * (N+1)
L = 0
for i in range(N):
lo = 1
hi = L
while lo <= hi:
mid = (lo+hi)//2
if (X[M[mid]] < X[i]):
lo = mid+1
else:
hi = mid-1
... | let longest l = List.fold_left (fun acc x -> if List.length acc < List.length x
then x
else acc) [] l
let subsequences d l =
let rec check_subsequences acc = function
| x::s -> check_subsequences (if (List.hd (List.rev x)) < d
... |
Change the programming language of this snippet from Python to OCaml without modifying what it does. | import math
szamok=[]
limit = 1000
for i in range(1,int(math.ceil(math.sqrt(limit))),2):
num = i*i
if (num < 1000 and num > 99):
szamok.append(num)
print(szamok)
| let odd_square x =
if x land 1 = 0
then None
else Some (x * x)
let () =
Seq.(ints 10 |> filter_map odd_square |> take_while ((>) 1000) |> iter (Printf.printf " %u"))
|
Keep all operations the same but rewrite the snippet in OCaml. |
def isPrime(n):
for i in range(2, int(n**0.5) + 1):
if n % i == 0:
return False
return True
def digSum(n, b):
s = 0
while n:
s += (n % b)
n = n // b
return s
if __name__ == '__main__':
for n in range(11, 99):
if isPrime(digSum(n**3, 10)) an... | let is_prime n =
let rec test x =
let q = n / x in x > q || x * q <> n && n mod (x + 2) <> 0 && test (x + 6)
in if n < 5 then n lor 1 = 3 else n land 1 <> 0 && n mod 3 <> 0 && test 5
let rec digit_sum n =
if n < 10 then n else n mod 10 + digit_sum (n / 10)
let is_square_and_cube_digit_sum_prime n =
is_pri... |
Write the same algorithm in OCaml as shown in this Python implementation. | python
Python 2.6.1 (r261:67517, Dec 4 2008, 16:51:00) [MSC v.1500 32 bit (Intel)] on
win32
Type "help", "copyright", "credits" or "license" for more information.
>>> def f(string1, string2, separator):
return separator.join([string1, '', string2])
>>> f('Rosetta', 'Code', ':')
'Rosetta::Code'
>>>
| $ ocaml
Objective Caml version 3.12.1
# let f s1 s2 sep = String.concat sep [s1; ""; s2];;
val f : string -> string -> string -> string = <fun>
# f "Rosetta" "Code" ":";;
- : string = "Rosetta::Code"
#
|
Generate a OCaml translation of this Python snippet without changing its computational steps. |
var x = 0
var y = 0
There are also multi-line comments
Everything inside of
]
discard
|
*)
|
Please provide an equivalent version of this Python code in OCaml. | limit = 1000
print("working...")
def isprime(n):
for i in range(2,int(n**0.5)+1):
if n%i==0:
return False
return True
def issquare(x):
for n in range(1,x+1):
if (x == n*n):
return 1
return 0
for n in range(limit-1):
if issquare(n) and isprime(n+1):
print(n,end=" ")
print()
prin... | let is_prime n =
let rec test x =
x * x > n || n mod x <> 0 && n mod (x + 2) <> 0 && test (x + 6)
in if n < 5 then n lor 1 = 3 else n land 1 <> 0 && n mod 3 <> 0 && test 5
let seq_squares =
let rec next n a () = Seq.Cons (n, next (n + a) (a + 2)) in
next 0 1
let () =
let cond n = is_prime (succ n) in
... |
Port the following code from Python to OCaml with equivalent syntax and logic. | limit = 1000
print("working...")
def isprime(n):
for i in range(2,int(n**0.5)+1):
if n%i==0:
return False
return True
def issquare(x):
for n in range(1,x+1):
if (x == n*n):
return 1
return 0
for n in range(limit-1):
if issquare(n) and isprime(n+1):
print(n,end=" ")
print()
prin... | let is_prime n =
let rec test x =
x * x > n || n mod x <> 0 && n mod (x + 2) <> 0 && test (x + 6)
in if n < 5 then n lor 1 = 3 else n land 1 <> 0 && n mod 3 <> 0 && test 5
let seq_squares =
let rec next n a () = Seq.Cons (n, next (n + a) (a + 2)) in
next 0 1
let () =
let cond n = is_prime (succ n) in
... |
Port the provided Python code into OCaml while preserving the original functionality. |
from itertools import count
def firstSquareWithPrefix(n):
pfx = str(n)
lng = len(pfx)
return int(
next(
s for s in (
str(x * x) for x in count(0)
)
if pfx == s[0:lng]
)
)
def main():
print('\n'.join([
str(... | let rec is_prefix a b =
if b > a then is_prefix a (b/10) else a = b
let rec smallest ?(i=1) n =
let square = i*i in
if is_prefix n square then square else smallest n ~i:(succ i)
let _ =
for n = 1 to 49 do
Printf.printf "%d%c" (smallest n) (if n mod 10 = 0 then '\n' else '\t')
done
|
Convert this Python block to OCaml, preserving its control flow and logic. |
from itertools import count
def firstSquareWithPrefix(n):
pfx = str(n)
lng = len(pfx)
return int(
next(
s for s in (
str(x * x) for x in count(0)
)
if pfx == s[0:lng]
)
)
def main():
print('\n'.join([
str(... | let rec is_prefix a b =
if b > a then is_prefix a (b/10) else a = b
let rec smallest ?(i=1) n =
let square = i*i in
if is_prefix n square then square else smallest n ~i:(succ i)
let _ =
for n = 1 to 49 do
Printf.printf "%d%c" (smallest n) (if n mod 10 = 0 then '\n' else '\t')
done
|
Write a version of this Python function in OCaml with identical behavior. | from collections import namedtuple
from math import sqrt
Pt = namedtuple('Pt', 'x, y')
Circle = Cir = namedtuple('Circle', 'x, y, r')
def circles_from_p1p2r(p1, p2, r):
'Following explanation at http://mathforum.org/library/drmath/view/53027.html'
if r == 0.0:
raise ValueError('radius of zero')
(x... |
type point = float * float
type radius = float
type circle = Circle of radius * point
type circ_output =
NoSolution
| OneSolution of circle
| TwoSolutions of circle * circle
| InfiniteSolutions
;;
let circles_2points_radius (x1, y1 : point) (x2, y2 : point) (r : radius) =
let (dx, dy) = (x2 -.... |
Change the programming language of this snippet from Python to OCaml without modifying what it does. | from collections import namedtuple
from math import sqrt
Pt = namedtuple('Pt', 'x, y')
Circle = Cir = namedtuple('Circle', 'x, y, r')
def circles_from_p1p2r(p1, p2, r):
'Following explanation at http://mathforum.org/library/drmath/view/53027.html'
if r == 0.0:
raise ValueError('radius of zero')
(x... |
type point = float * float
type radius = float
type circle = Circle of radius * point
type circ_output =
NoSolution
| OneSolution of circle
| TwoSolutions of circle * circle
| InfiniteSolutions
;;
let circles_2points_radius (x1, y1 : point) (x2, y2 : point) (r : radius) =
let (dx, dy) = (x2 -.... |
Preserve the algorithm and functionality while converting the code from Python to OCaml. | import pyaudio
chunk = 1024
FORMAT = pyaudio.paInt16
CHANNELS = 1
RATE = 44100
p = pyaudio.PyAudio()
stream = p.open(format = FORMAT,
channels = CHANNELS,
rate = RATE,
input = True,
frames_per_buffer = chunk)
data = stream.read(chunk)
print [ord(i) for... | #load "unix.cma"
let record bytes =
let buf = String.make bytes '\000' in
let ic = open_in "/dev/dsp" in
let chunk = 4096 in
for i = 0 to pred (bytes / chunk) do
ignore (input ic buf (i * chunk) chunk)
done;
close_in ic;
(buf)
let play buf len =
let oc = open_out "/dev/dsp" in
output_string oc... |
Produce a language-to-language conversion: from Python to OCaml, same semantics. |
import turtle as t
def sier(n,length):
if n == 0:
return
for i in range(3):
sier(n - 1, length / 2)
t.fd(length)
t.rt(120)
| open Graphics
let round v =
int_of_float (floor (v +. 0.5))
let middle (x1, y1) (x2, y2) =
((x1 +. x2) /. 2.0,
(y1 +. y2) /. 2.0)
let draw_line (x1, y1) (x2, y2) =
moveto (round x1) (round y1);
lineto (round x2) (round y2);
;;
let draw_triangle (p1, p2, p3) =
draw_line p1 p2;
draw_line p2 p3;
draw_... |
Convert this Python snippet to OCaml and keep its semantics consistent. |
import turtle as t
def sier(n,length):
if n == 0:
return
for i in range(3):
sier(n - 1, length / 2)
t.fd(length)
t.rt(120)
| open Graphics
let round v =
int_of_float (floor (v +. 0.5))
let middle (x1, y1) (x2, y2) =
((x1 +. x2) /. 2.0,
(y1 +. y2) /. 2.0)
let draw_line (x1, y1) (x2, y2) =
moveto (round x1) (round y1);
lineto (round x2) (round y2);
;;
let draw_triangle (p1, p2, p3) =
draw_line p1 p2;
draw_line p2 p3;
draw_... |
Can you help me rewrite this code in OCaml instead of Python, keeping it the same logically? |
from PIL import Image
im = Image.open("boxes_1.jpg")
im.save("boxes_1v2.ppm")
| let read_image ~filename =
if not(Sys.file_exists filename)
then failwith(Printf.sprintf "the file %s does not exist" filename);
let cmd = Printf.sprintf "convert \"%s\" ppm:-" filename in
let ic, oc = Unix.open_process cmd in
let img = read_ppm ~ic in
(img)
;;
|
Write the same algorithm in OCaml as shown in this Python implementation. | def setup():
size(500, 500)
generate_voronoi_diagram(width, height, 25)
saveFrame("VoronoiDiagram.png")
def generate_voronoi_diagram(w, h, num_cells):
nx, ny, nr, ng, nb = [], [], [], [], []
for i in range(num_cells):
nx.append(int(random(w)))
ny.append(int(random(h)))
nr.a... | let n_sites = 220
let size_x = 640
let size_y = 480
let sq2 ~x ~y =
(x * x + y * y)
let rand_int_range a b =
a + Random.int (b - a + 1)
let nearest_site ~site ~x ~y =
let ret = ref 0 in
let dist = ref 0 in
Array.iteri (fun k (sx, sy) ->
let d = sq2 (x - sx) (y - sy) in
if k = 0 || d < !dist the... |
Port the provided Python code into OCaml while preserving the original functionality. | def setup():
size(500, 500)
generate_voronoi_diagram(width, height, 25)
saveFrame("VoronoiDiagram.png")
def generate_voronoi_diagram(w, h, num_cells):
nx, ny, nr, ng, nb = [], [], [], [], []
for i in range(num_cells):
nx.append(int(random(w)))
ny.append(int(random(h)))
nr.a... | let n_sites = 220
let size_x = 640
let size_y = 480
let sq2 ~x ~y =
(x * x + y * y)
let rand_int_range a b =
a + Random.int (b - a + 1)
let nearest_site ~site ~x ~y =
let ret = ref 0 in
let dist = ref 0 in
Array.iteri (fun k (sx, sy) ->
let d = sq2 (x - sx) (y - sy) in
if k = 0 || d < !dist the... |
Rewrite this program in OCaml while keeping its functionality equivalent to the Python version. | def merge_list(a, b):
out = []
while len(a) and len(b):
if a[0] < b[0]:
out.append(a.pop(0))
else:
out.append(b.pop(0))
out += a
out += b
return out
def strand(a):
i, s = 0, [a.pop(0)]
while i < len(a):
if a[i] > s[-1]:
s.append(a.pop(i))
else:
i += 1
return s
def strand_sort(a):
out = st... | let rec strand_sort (cmp : 'a -> 'a -> int) : 'a list -> 'a list = function
[] -> []
| x::xs ->
let rec extract_strand x = function
[] -> [x], []
| x1::xs when cmp x x1 <= 0 ->
let strand, rest = extract_strand x1 xs in x::strand, rest
| x1::xs ->
let strand, rest = extract_strand x ... |
Please provide an equivalent version of this Python code in OCaml. | import numpy as np
import matplotlib.pyplot as plt
def iterate(grid):
changed = False
for ii, arr in enumerate(grid):
for jj, val in enumerate(arr):
if val > 3:
grid[ii, jj] -= 4
if ii > 0:
grid[ii - 1, jj] += 1
if ii < le... | module Make =
functor (M : sig val m : int val n : int end)
-> struct
let grid = Array.init M.m (fun _ -> Array.make M.n 0)
let print () =
for i = 0 to M.m - 1
do for j = 0 to M.n - 1
do Printf.printf "%d " grid.(i).(j)
done
; print_newline ()
done
let unst... |
Please provide an equivalent version of this Python code in OCaml. | import numpy as np
import matplotlib.pyplot as plt
def iterate(grid):
changed = False
for ii, arr in enumerate(grid):
for jj, val in enumerate(arr):
if val > 3:
grid[ii, jj] -= 4
if ii > 0:
grid[ii - 1, jj] += 1
if ii < le... | module Make =
functor (M : sig val m : int val n : int end)
-> struct
let grid = Array.init M.m (fun _ -> Array.make M.n 0)
let print () =
for i = 0 to M.m - 1
do for j = 0 to M.n - 1
do Printf.printf "%d " grid.(i).(j)
done
; print_newline ()
done
let unst... |
Write a version of this Python function in OCaml with identical behavior. | import autopy
autopy.key.type_string("Hello, world!")
autopy.key.type_string("Hello, world!", wpm=60)
autopy.key.tap(autopy.key.Code.RETURN)
autopy.key.tap(autopy.key.Code.F1)
autopy.key.tap(autopy.key.Code.LEFT_ARROW)
| open Xlib
let () =
let d = xOpenDisplay "" in
let s = xDefaultScreen d in
Random.self_init();
let w = xCreateSimpleWindow d (xRootWindow d s) 10 10 300 200 1
(xBlackPixel d s) (xWhitePixel d s) in
xStoreName d w Sys.argv.(0);
xSelectInput d w [ExposureMask; K... |
Ensure the translated OCaml code behaves exactly like the original Python snippet. |
def maxDeltas(ns):
pairs = [
(abs(a - b), (a, b)) for a, b
in zip(ns, ns[1:])
]
delta = max(pairs, key=lambda ab: ab[0])[0]
return [
ab for ab in pairs
if delta == ab[0]
]
def main():
maxPairs = maxDeltas([
1, 8, 2, -3, 0, 1, 1, -2.3, 0... | let rec fold_pairwise f m = function
| a :: (b :: _ as t) -> fold_pairwise f (f m a b) t
| _ -> m
let pair_to_str (a, b) =
Printf.sprintf "(%g, %g)" a b
let max_diffs =
let next m a b =
match abs_float (b -. a), m with
| d', (d, _) when d' > d -> d', [a, b]
| d', (d, l) when d' = d -> d', (a, b) :... |
Write the same algorithm in OCaml as shown in this Python implementation. | import operator
class AstNode(object):
def __init__( self, opr, left, right ):
self.opr = opr
self.l = left
self.r = right
def eval(self):
return self.opr(self.l.eval(), self.r.eval())
class LeafNode(object):
def __init__( self, valStrg ):
self.v = int(valStrg)
def eval(sel... | type expression =
| Const of float
| Sum of expression * expression
| Diff of expression * expression
| Prod of expression * expression
| Quot of expression * expression
let rec eval = function
| Const c -> c
| Sum (f, g) -> eval f +. eval g
| Diff(f, g) -> eval f -. eval g
| Prod(f, g) ... |
Write the same algorithm in OCaml as shown in this Python implementation. | import operator
class AstNode(object):
def __init__( self, opr, left, right ):
self.opr = opr
self.l = left
self.r = right
def eval(self):
return self.opr(self.l.eval(), self.r.eval())
class LeafNode(object):
def __init__( self, valStrg ):
self.v = int(valStrg)
def eval(sel... | type expression =
| Const of float
| Sum of expression * expression
| Diff of expression * expression
| Prod of expression * expression
| Quot of expression * expression
let rec eval = function
| Const c -> c
| Sum (f, g) -> eval f +. eval g
| Diff(f, g) -> eval f -. eval g
| Prod(f, g) ... |
Preserve the algorithm and functionality while converting the code from Python to OCaml. | import sys
import pygame
pygame.init()
clk = pygame.time.Clock()
if pygame.joystick.get_count() == 0:
raise IOError("No joystick detected")
joy = pygame.joystick.Joystick(0)
joy.init()
size = width, height = 600, 600
screen = pygame.display.set_mode(size)
pygame.display.set_caption("Joystick Tester")
frame... | let remove x = List.filter (fun y -> y <> x)
let buttons_string b =
String.concat " " (List.map string_of_int b)
let position app x y =
let view = SFRenderWindow.getView app in
let width, height = SFView.getSize view in
let hw = width /. 2.0 in
let hh = height /. 2.0 in
(hw +. ((x /. 100.0) *. hw),
hh ... |
Produce a functionally identical OCaml code for the snippet given in Python. |
from re import sub
testtexts = [
,
,
]
for txt in testtexts:
text2 = sub(r'<lang\s+\"?([\w\d\s]+)\"?\s?>', r'<syntaxhighlight lang=\1>', txt)
text2 = sub(r'<lang\s*>', r'<syntaxhighlight lang=text>', text2)
text2 = sub(r'</lang\s*>', r'
| #load "str.cma"
let langs =
Str.split (Str.regexp " ")
"actionscript ada algol68 amigae applescript autohotkey awk bash basic \
befunge bf c cfm cobol cpp csharp d delphi e eiffel factor false forth \
fortran fsharp haskell haxe j java javascript lisaac lisp logo lua m4 \
mathematica maxscript mo... |
Port the following code from Python to OCaml with equivalent syntax and logic. |
from math import gcd
from functools import reduce
def lcm(a, b):
return 0 if 0 == a or 0 == b else (
abs(a * b) // gcd(a, b)
)
for i in [10, 20, 200, 2000]:
print(str(i) + ':', reduce(lcm, range(1, i + 1)))
| let rec gcd a = function
| 0 -> a
| b -> gcd b (a mod b)
let lcm a b =
a * b / gcd a b
let smallest_multiple n =
Seq.(ints 1 |> take n |> fold_left lcm 1)
let () =
Printf.printf "%u\n" (smallest_multiple 20)
|
Change the following Python code into OCaml without altering its purpose. | import math
def SquareFree ( _number ) :
max = (int) (math.sqrt ( _number ))
for root in range ( 2, max+1 ):
if 0 == _number % ( root * root ):
return False
return True
def ListSquareFrees( _start, _end ):
count = 0
for i in range ( _start, _end+1 ):
if True == SquareFree( i ):
print ( "{}\t".fo... | let squarefree (number: int) : bool =
let max = Float.of_int number |> sqrt |> Float.to_int |> (fun x -> x + 2) in
let rec inner i number2 =
if i == max
then true
else if number2 mod (i*i) == 0
then false
else inner (i+1) number2
in inner 2 number
;;
let li... |
Can you help me rewrite this code in OCaml instead of Python, keeping it the same logically? | class DigitSumer :
def __init__(self):
sumdigit = lambda n : sum( map( int,str( n )))
self.t = [sumdigit( i ) for i in xrange( 10000 )]
def __call__ ( self,n ):
r = 0
while n >= 10000 :
n,q = divmod( n,10000 )
r += self.t[q]
return r + self.t[n]
... | open List;
val rec selfNumberNr = fn NR =>
let
val rec sumdgt = fn 0 => 0 | n => Int.rem (n, 10) + sumdgt (Int.quot(n ,10));
val rec isSelf = fn ([],l1,l2) => []
| (x::tt,l1,l2) => if exists (fn i=>i=x) l1 orelse exists (fn i=>i=x) l2
then ( isSelf (tt,l1,l2)) else x::isSelf (tt,l1,l2) ;
val rec partco... |
Please provide an equivalent version of this Python code in OCaml. | from collections import defaultdict
def hashJoin(table1, index1, table2, index2):
h = defaultdict(list)
for s in table1:
h[s[index1]].append(s)
return [(s, r) for r in table2 for s in h[r[index2]]]
table1 = [(27, "Jonah"),
(18, "Alan"),
(28, "Glory"),
(18, "... | let hash_join table1 f1 table2 f2 =
let h = Hashtbl.create 42 in
List.iter (fun s ->
Hashtbl.add h (f1 s) s) table1;
List.concat (List.map (fun r ->
List.map (fun s -> s, r) (Hashtbl.find_all h (f2 r))) table2)
|
Write the same algorithm in OCaml as shown in this Python implementation. | import time
import os
seconds = input("Enter a number of seconds: ")
sound = input("Enter an mp3 filename: ")
time.sleep(float(seconds))
os.startfile(sound + ".mp3")
| let rec wait n = match n with
| 0 -> ()
| n -> Sys.command "sleep 1"; wait (n - 1);;
Printf.printf "Please enter a number of seconds\n";;
let time = read_int ();;
Printf.printf "Please enter a file name\n";;
let fileName = (read_line ()) ^ ".mp3";;
wait time;;
Sys.command ("mpg123 " ^ fileName);;
|
Generate an equivalent OCaml version of this Python code. |
from __future__ import division, print_function
from itertools import permutations, combinations, product, \
chain
from pprint import pprint as pp
from fractions import Fraction as F
import random, ast, re
import sys
if sys.version_info[0] < 3:
input = raw_input
from ... | type expression =
| Const of float
| Sum of expression * expression
| Diff of expression * expression
| Prod of expression * expression
| Quot of expression * expression
let rec eval = function
| Const c -> c
| Sum (f, g) -> eval f +. eval g
| Diff(f, g) -> eval f -. eval g
| Prod(f, g)... |
Change the programming language of this snippet from Python to OCaml without modifying what it does. |
from __future__ import division, print_function
from itertools import permutations, combinations, product, \
chain
from pprint import pprint as pp
from fractions import Fraction as F
import random, ast, re
import sys
if sys.version_info[0] < 3:
input = raw_input
from ... | type expression =
| Const of float
| Sum of expression * expression
| Diff of expression * expression
| Prod of expression * expression
| Quot of expression * expression
let rec eval = function
| Const c -> c
| Sum (f, g) -> eval f +. eval g
| Diff(f, g) -> eval f -. eval g
| Prod(f, g)... |
Convert this Python block to OCaml, preserving its control flow and logic. | def legendre(a, p):
return pow(a, (p - 1) // 2, p)
def tonelli(n, p):
assert legendre(n, p) == 1, "not a square (mod p)"
q = p - 1
s = 0
while q % 2 == 0:
q //= 2
s += 1
if s == 1:
return pow(n, (p + 1) // 4, p)
for z in range(2, p):
if p - 1 == legendre(z, p... | let tonelli n p =
let open Z in
let two = ~$2 in
let pp = pred p in
let pph = pred p / two in
let pow_mod_p a e = powm a e p in
let legendre_p a = pow_mod_p a pph in
if legendre_p n <> one then None
else
let s = trailing_zeros pp in
if s = 1 then
let r = pow_mod_p n (succ p / ~$4) in
... |
Change the following Python code into OCaml without altering its purpose. | def legendre(a, p):
return pow(a, (p - 1) // 2, p)
def tonelli(n, p):
assert legendre(n, p) == 1, "not a square (mod p)"
q = p - 1
s = 0
while q % 2 == 0:
q //= 2
s += 1
if s == 1:
return pow(n, (p + 1) // 4, p)
for z in range(2, p):
if p - 1 == legendre(z, p... | let tonelli n p =
let open Z in
let two = ~$2 in
let pp = pred p in
let pph = pred p / two in
let pow_mod_p a e = powm a e p in
let legendre_p a = pow_mod_p a pph in
if legendre_p n <> one then None
else
let s = trailing_zeros pp in
if s = 1 then
let r = pow_mod_p n (succ p / ~$4) in
... |
Ensure the translated OCaml code behaves exactly like the original Python snippet. |
from __future__ import annotations
from typing import Any
from typing import Callable
from typing import Generic
from typing import Optional
from typing import TypeVar
from typing import Union
T = TypeVar("T")
class Maybe(Generic[T]):
def __init__(self, value: Union[Optional[T], Maybe[T]] = None):
if ... | let bind opt func = match opt with
| Some x -> func x
| None -> None
let return x = Some x
|
Keep all operations the same but rewrite the snippet in OCaml. |
from __future__ import annotations
from itertools import chain
from typing import Any
from typing import Callable
from typing import Iterable
from typing import List
from typing import TypeVar
T = TypeVar("T")
class MList(List[T]):
@classmethod
def unit(cls, value: Iterable[T]) -> MList[T]:
return... | let bind : 'a list -> ('a -> 'b list) -> 'b list =
fun l f -> List.flatten (List.map f l)
let return x = [x]
|
Rewrite this program in OCaml while keeping its functionality equivalent to the Python version. | from collections import defaultdict
import urllib.request
CH2NUM = {ch: str(num) for num, chars in enumerate('abc def ghi jkl mno pqrs tuv wxyz'.split(), 2) for ch in chars}
URL = 'http://www.puzzlers.org/pub/wordlists/unixdict.txt'
def getwords(url):
return urllib.request.urlopen(url).read().decode("utf-8").lower(... | module IntMap = Map.Make(Int)
let seq_lines ch =
let rec repeat () =
match input_line ch with
| s -> Seq.Cons (s, repeat)
| exception End_of_file -> Nil
in repeat
let key_of_char = function
| 'a' .. 'c' -> Some 1
| 'd' .. 'f' -> Some 2
| 'g' .. 'i' -> Some 3
| 'j' .. 'l' -> Some 4
| 'm' ..... |
Rewrite this program in OCaml while keeping its functionality equivalent to the Python version. |
gridsize = (6, 4)
minerange = (0.2, 0.6)
try:
raw_input
except:
raw_input = input
import random
from itertools import product
from pprint import pprint as pp
def gridandmines(gridsize=gridsize, minerange=minerange):
xgrid, ygrid = gridsize
minmines, maxmines = minerange
minecount = xgri... | exception Lost
exception Won
let put_mines g m n mines_number =
let rec aux i =
if i < mines_number then
begin
let x = Random.int n
and y = Random.int m in
if g.(y).(x)
then aux i
else begin
g.(y).(x) <- true;
aux (succ i)
end
end
in
aux 0
let prin... |
Produce a language-to-language conversion: from Python to OCaml, same semantics. |
from itertools import repeat
from functools import reduce
def churchZero():
return lambda f: identity
def churchSucc(cn):
return lambda f: compose(f)(cn(f))
def churchAdd(m):
return lambda n: lambda f: compose(m(f))(n(f))
def churchMult(m):
return lambda n: compose(m)(n)
... |
type church_num = { f : 'a. ('a -> 'a) -> 'a -> 'a }
let ch_zero : church_num = { f = fun _ -> fun x -> x }
let ch_one : church_num = { f = fun fn -> fn }
let ch_succ (c : church_num) : church_num = { f = fun fn x -> fn (c.f fn x) }
let ch_add (m : church_num) (n : church_num) : church_num =
{ f = fun fn ... |
Convert the following code from Python to OCaml, ensuring the logic remains intact. |
from itertools import repeat
from functools import reduce
def churchZero():
return lambda f: identity
def churchSucc(cn):
return lambda f: compose(f)(cn(f))
def churchAdd(m):
return lambda n: lambda f: compose(m(f))(n(f))
def churchMult(m):
return lambda n: compose(m)(n)
... |
type church_num = { f : 'a. ('a -> 'a) -> 'a -> 'a }
let ch_zero : church_num = { f = fun _ -> fun x -> x }
let ch_one : church_num = { f = fun fn -> fn }
let ch_succ (c : church_num) : church_num = { f = fun fn x -> fn (c.f fn x) }
let ch_add (m : church_num) (n : church_num) : church_num =
{ f = fun fn ... |
Rewrite the snippet below in OCaml so it works the same as the original Python code. | names = sorted((set(globals().keys()) | set(__builtins__.__dict__.keys())) - set('_ names i'.split()))
print( '\n'.join(' '.join(names[i:i+8]) for i in range(0, len(names), 8)) )
| val argv : string array
val executable_name : string
val interactive : bool ref
val os_type : string
val word_size : int
val max_string_length : int
val max_array_length : int
val ocaml_version : string
|
Write the same algorithm in OCaml as shown in this Python implementation. |
import sys
from socket import inet_aton, inet_ntoa
from struct import pack, unpack
args = sys.argv[1:]
if len(args) == 0:
args = sys.stdin.readlines()
for cidr in args:
dotted, size_str = cidr.split('/')
size = int(size_str)
numeric = unpack('!I', inet_aton(dotted))[0]
binary = f'{numeric:
... | let mask = function
| _, 0 -> 0l, 0
| a, l -> Int32.(logand (shift_left minus_one (-l land 31)) a), l
let str_to_cidr s =
let (<<+) b a = Int32.(add (shift_left b 8) a) in
let recv d c b a l = d <<+ c <<+ b <<+ a, l in
Scanf.sscanf s "%3lu.%3lu.%3lu.%3lu/%2u" recv
let cidr_to_str (a, l) =
let addr n =
... |
Change the programming language of this snippet from Python to OCaml without modifying what it does. |
import sys
from socket import inet_aton, inet_ntoa
from struct import pack, unpack
args = sys.argv[1:]
if len(args) == 0:
args = sys.stdin.readlines()
for cidr in args:
dotted, size_str = cidr.split('/')
size = int(size_str)
numeric = unpack('!I', inet_aton(dotted))[0]
binary = f'{numeric:
... | let mask = function
| _, 0 -> 0l, 0
| a, l -> Int32.(logand (shift_left minus_one (-l land 31)) a), l
let str_to_cidr s =
let (<<+) b a = Int32.(add (shift_left b 8) a) in
let recv d c b a l = d <<+ c <<+ b <<+ a, l in
Scanf.sscanf s "%3lu.%3lu.%3lu.%3lu/%2u" recv
let cidr_to_str (a, l) =
let addr n =
... |
Preserve the algorithm and functionality while converting the code from Python to OCaml. | from decimal import *
D = Decimal
getcontext().prec = 100
a = n = D(1)
g, z, half = 1 / D(2).sqrt(), D(0.25), D(0.5)
for i in range(18):
x = [(a + g) * half, (a * g).sqrt()]
var = x[0] - a
z -= var * var * n
n += n
a, g = x
print(a * a / z)
| let limit = 10000 and n = 2800
let x = Array.make (n+1) 2000
let rec g j sum =
if j < 1 then sum else
let sum = sum * j + limit * x.(j) in
x.(j) <- sum mod (j * 2 - 1);
g (j - 1) (sum / (j * 2 - 1))
let rec f i carry =
if i = 0 then () else
let sum = g i 0 in
Printf.printf "%04d" (carry + sum ... |
Translate this program into OCaml but keep the logic exactly as in Python. | from decimal import *
D = Decimal
getcontext().prec = 100
a = n = D(1)
g, z, half = 1 / D(2).sqrt(), D(0.25), D(0.5)
for i in range(18):
x = [(a + g) * half, (a * g).sqrt()]
var = x[0] - a
z -= var * var * n
n += n
a, g = x
print(a * a / z)
| let limit = 10000 and n = 2800
let x = Array.make (n+1) 2000
let rec g j sum =
if j < 1 then sum else
let sum = sum * j + limit * x.(j) in
x.(j) <- sum mod (j * 2 - 1);
g (j - 1) (sum / (j * 2 - 1))
let rec f i carry =
if i = 0 then () else
let sum = g i 0 in
Printf.printf "%04d" (carry + sum ... |
Change the programming language of this snippet from Python to OCaml without modifying what it does. | from Xlib import X, display
class Window:
def __init__(self, display, msg):
self.display = display
self.msg = msg
self.screen = self.display.screen()
self.window = self.screen.root.create_window(
10, 10, 100, 100, 1,
self.screen.root_depth,
... | open Xlib
let () =
let d = xOpenDisplay "" in
let s = xDefaultScreen d in
let w = xCreateSimpleWindow d (xRootWindow d s) 10 10 100 100 1
(xBlackPixel d s) (xWhitePixel d s) in
xSelectInput d w [ExposureMask; KeyPressMask];
xMapWindow d w;
let msg = "Hello, World!" in
le... |
Translate the given Python code snippet into OCaml without altering its behavior. | from numpy import *
def Legendre(n,x):
x=array(x)
if (n==0):
return x*0+1.0
elif (n==1):
return x
else:
return ((2.0*n-1.0)*x*Legendre(n-1,x)-(n-1)*Legendre(n-2,x))/n
def DLegendre(n,x):
x=array(x)
if (n==0):
return x*0
elif (n==1):
return x*0+1.0
else:
return (n/(x**2-1.0))*(x*Legendre(n,x)... | let rec leg n x = match n with
| 0 -> 1.0
| 1 -> x
| k -> let u = 1.0 -. 1.0 /. float k in
(1.0+.u)*.x*.(leg (k-1) x) -. u*.(leg (k-2) x);;
let leg' n x = match n with
| 0 -> 0.0
| 1 -> 1.0
| _ -> ((leg (n-1) x) -. x*.(leg n x)) *. (float n)/.(1.0-.x*.x);;
let approx_root k n =
let pi = ... |
Produce a functionally identical OCaml code for the snippet given in Python. | from PIL import Image
if __name__=="__main__":
im = Image.open("frog.png")
im2 = im.quantize(16)
im2.show()
| let rem_from rem from =
List.filter ((<>) rem) from
let float_rgb (r,g,b) =
(float r, float g, float b)
let round x =
int_of_float (floor (x +. 0.5))
let int_rgb (r,g,b) =
(round r, round g, round b)
let rgb_add (r1,g1,b1) (r2,g2,b2) =
(r1 +. r2,
g1 +. g2,
b1 +. b2)
let rgb_mean px_list =
let n... |
Translate this program into OCaml but keep the logic exactly as in Python. | from collections import namedtuple
from pprint import pprint as pp
OpInfo = namedtuple('OpInfo', 'prec assoc')
L, R = 'Left Right'.split()
ops = {
'^': OpInfo(prec=4, assoc=R),
'*': OpInfo(prec=3, assoc=L),
'/': OpInfo(prec=3, assoc=L),
'+': OpInfo(prec=2, assoc=L),
'-': OpInfo(prec=2, assoc=L),
'(': OpInfo(pre... | type associativity = Left | Right;;
let prec op =
match op with
| "^" -> 4
| "*" -> 3
| "/" -> 3
| "+" -> 2
| "-" -> 2
| _ -> -1;;
let assoc op =
match op with
| "^" -> Right
| _ -> Left;;
let split_while p =
let rec go ls xs =
match xs with
| x::xs' when p x -> go (x::ls) xs'
| ... |
Convert this Python snippet to OCaml and keep its semantics consistent. | import math
def perlin_noise(x, y, z):
X = math.floor(x) & 255
Y = math.floor(y) & 255
Z = math.floor(z) & 255
x -= math.floor(x)
y -= math.floor(y)
z -= math.floor(z)
u = fade(x) ... | let permutation = [151;160;137;91;90;15;
131;13;201;95;96;53;194;233;7;225;140;36;103;30;69;142;8;99;37;240;21;10;23;
190; 6;148;247;120;234;75;0;26;197;62;94;252;219;203;117;35;11;32;57;177;33;
88;237;149;56;87;174;20;125;136;171;168; 68;175;74;165;71;134;139;48;27;166;
77;146;158;231;83;111;229;122;60;211;133;230;220... |
Change the following Python code into OCaml without altering its purpose. |
import os
from math import pi, sin
au_header = bytearray(
[46, 115, 110, 100,
0, 0, 0, 24,
255, 255, 255, 255,
0, 0, 0, 3,
0, 0, 172, 68,
0, 0, 0, 1])
def f(x, freq):
"Compute sine wave as 16-bi... | module BA = Bigarray
module BA1 = Bigarray.Array1
let () =
let samples = 44100 in
let sample_rate = 44100 in
let amplitude = 30000. in
let raw = BA1.create BA.int16_signed BA.c_layout samples in
let two_pi = 6.28318 in
let increment = 440.0 /. 44100.0 in
let x = ref 0.0 in
for i = 0 to samples - 1... |
Can you help me rewrite this code in OCaml instead of Python, keeping it the same logically? | from __future__ import print_function
import matplotlib.pyplot as plt
class AStarGraph(object):
def __init__(self):
self.barriers = []
self.barriers.append([(2,4),(2,5),(2,6),(3,6),(4,6),(5,6),(5,5),(5,4),(5,3),(5,2),(4,2),(3,2)])
def heuristic(self, start, goal):
D = 1
D2 = 1
dx = abs(start[0] -... | module IntPairs =
struct
type t = int * int
let compare (x0,y0) (x1,y1) =
match Stdlib.compare x0 x1 with
| 0 -> Stdlib.compare y0 y1
| c -> c
end
module PairsMap = Map.Make(IntPairs)
module PairsSet = Set.Make(IntPairs)
let find_path start goal board =
let max_y = Array.length board ... |
Translate the given Python code snippet into OCaml without altering its behavior. | from __future__ import print_function
import matplotlib.pyplot as plt
class AStarGraph(object):
def __init__(self):
self.barriers = []
self.barriers.append([(2,4),(2,5),(2,6),(3,6),(4,6),(5,6),(5,5),(5,4),(5,3),(5,2),(4,2),(3,2)])
def heuristic(self, start, goal):
D = 1
D2 = 1
dx = abs(start[0] -... | module IntPairs =
struct
type t = int * int
let compare (x0,y0) (x1,y1) =
match Stdlib.compare x0 x1 with
| 0 -> Stdlib.compare y0 y1
| c -> c
end
module PairsMap = Map.Make(IntPairs)
module PairsSet = Set.Make(IntPairs)
let find_path start goal board =
let max_y = Array.length board ... |
Change the following Python code into OCaml without altering its purpose. | import re
from fractions import Fraction
from pprint import pprint as pp
equationtext =
def parse_eqn(equationtext=equationtext):
eqn_re = re.compile(r)
found = eqn_re.findall(equationtext)
machins, part = [], []
for lhs, sign, mult, numer, denom in eqn_re.findall(equationtext):
if lhs and ... | open Num;;
let tadd p q = (p +/ q) // ((Int 1) -/ (p */ q)) in
let rec tan_expr (n,a,b) =
if n = 1 then (Int a)//(Int b) else
if n = -1 then (Int (-a))//(Int b) else
let m = n/2 in
let tm = tan_expr (m,a,b) in
let m2 = tadd tm tm and k = n-m-m in
if k = 0 then m2 else tadd (tan_expr (k,a,b)) m2 ... |
Transform the following Python implementation into OCaml, maintaining the same output and logic. | import re
from fractions import Fraction
from pprint import pprint as pp
equationtext =
def parse_eqn(equationtext=equationtext):
eqn_re = re.compile(r)
found = eqn_re.findall(equationtext)
machins, part = [], []
for lhs, sign, mult, numer, denom in eqn_re.findall(equationtext):
if lhs and ... | open Num;;
let tadd p q = (p +/ q) // ((Int 1) -/ (p */ q)) in
let rec tan_expr (n,a,b) =
if n = 1 then (Int a)//(Int b) else
if n = -1 then (Int (-a))//(Int b) else
let m = n/2 in
let tm = tan_expr (m,a,b) in
let m2 = tadd tm tm and k = n-m-m in
if k = 0 then m2 else tadd (tan_expr (k,a,b)) m2 ... |
Port the following code from Python to OCaml with equivalent syntax and logic. | v1 = PVector(5, 7)
v2 = PVector(2, 3)
println('{} {} {} {}\n'.format( v1.x, v1.y, v1.mag(), v1.heading()))
println(v1 + v2)
println(v1 - v2)
println(v1 * 11)
println(v1 / 2)
println('')
println(v1.sub(v1))
println(v1.add(v2))
println(v1.mult(10))
println(v1.div(10))
| module Vector =
struct
type t = { x : float; y : float }
let make x y = { x; y }
let add a b = { x = a.x +. b.x; y = a.y +. b.y }
let sub a b = { x = a.x -. b.x; y = a.y -. b.y }
let mul a n = { x = a.x *. n; y = a.y *. n }
let div a n = { x = a.x /. n; y = a.y /. n }
let to_string {x; y}... |
Convert this Python snippet to OCaml and keep its semantics consistent. |
class Point:
b = 7
def __init__(self, x=float('inf'), y=float('inf')):
self.x = x
self.y = y
def copy(self):
return Point(self.x, self.y)
def is_zero(self):
return self.x > 1e20 or self.x < -1e20
def neg(self):
return Point(self.x, -self.y)
def dbl(s... |
type ec_point = Point of float * float | Inf
type ec_curve = { a : float; b : float }
let cube_root : float -> float =
let third = 1. /. 3. in
let f x =
if x > 0.
then x ** third
else ~-. (~-. x ** third)
in
f
let ec_minx ({a; b} : ec_curve) : float =
let factor ... |
Please provide an equivalent version of this Python code in OCaml. |
class Point:
b = 7
def __init__(self, x=float('inf'), y=float('inf')):
self.x = x
self.y = y
def copy(self):
return Point(self.x, self.y)
def is_zero(self):
return self.x > 1e20 or self.x < -1e20
def neg(self):
return Point(self.x, -self.y)
def dbl(s... |
type ec_point = Point of float * float | Inf
type ec_curve = { a : float; b : float }
let cube_root : float -> float =
let third = 1. /. 3. in
let f x =
if x > 0.
then x ** third
else ~-. (~-. x ** third)
in
f
let ec_minx ({a; b} : ec_curve) : float =
let factor ... |
Convert this Python snippet to OCaml and keep its semantics consistent. | from array import array
from collections import deque
import psyco
data = []
nrows = 0
px = py = 0
sdata = ""
ddata = ""
def init(board):
global data, nrows, sdata, ddata, px, py
data = filter(None, board.splitlines())
nrows = max(len(r) for r in data)
maps = {' ':' ', '.': '.', '@':' ', '
mapd =... | type dir = U | D | L | R
type move_t = Move of dir | Push of dir
let letter = function
| Push(U) -> 'U' | Push(D) -> 'D' | Push(L) -> 'L' | Push(R) -> 'R'
| Move(U) -> 'u' | Move(D) -> 'd' | Move(L) -> 'l' | Move(R) -> 'r'
let cols = ref 0
let delta = function U -> -(!cols) | D -> !cols | L -> -1 | R -> 1
let ... |
Produce a language-to-language conversion: from Python to OCaml, same semantics. | hex2bin = dict('{:x} {:04b}'.format(x,x).split() for x in range(16))
bin2hex = dict('{:b} {:x}'.format(x,x).split() for x in range(16))
def float_dec2bin(d):
neg = False
if d < 0:
d = -d
neg = True
hx = float(d).hex()
p = hx.index('p')
bn = ''.join(hex2bin.get(char, char) for char i... | #load "str.cma"
module Convert : sig
type value = | Float of float
| String of string
val convert : ?from_base:int -> to_base:int -> value -> value
end =
struct
type value = | Float of float
| String of string
let min_base = 2
let max_base = 10 + int_of_char 'Z' - int_of_cha... |
Convert this Python block to OCaml, preserving its control flow and logic. | hex2bin = dict('{:x} {:04b}'.format(x,x).split() for x in range(16))
bin2hex = dict('{:b} {:x}'.format(x,x).split() for x in range(16))
def float_dec2bin(d):
neg = False
if d < 0:
d = -d
neg = True
hx = float(d).hex()
p = hx.index('p')
bn = ''.join(hex2bin.get(char, char) for char i... | #load "str.cma"
module Convert : sig
type value = | Float of float
| String of string
val convert : ?from_base:int -> to_base:int -> value -> value
end =
struct
type value = | Float of float
| String of string
let min_base = 2
let max_base = 10 + int_of_char 'Z' - int_of_cha... |
Translate this program into OCaml but keep the logic exactly as in Python. | from itertools import count
from itertools import islice
from typing import Iterable
from typing import Tuple
import gmpy2
def factorials() -> Iterable[int]:
fact = 1
for i in count(1):
yield fact
fact *= i
def factorial_primes() -> Iterable[Tuple[int, int, str]]:
for n, fact in enumera... | let is_prime (_, n, _) =
let rec test x =
let d = n / x in x > d || x * d <> n && n mod (x + 2) <> 0 && test (x + 6)
in
if n < 5
then n lor 1 = 3
else n land 1 <> 0 && n mod 3 <> 0 && test 5
let factorials_plus_minus_one =
let rec next x y () =
Seq.Cons ((x, pred y, 0), Seq.cons (x, succ y, 1) (nex... |
Change the programming language of this snippet from Python to OCaml without modifying what it does. | from __future__ import print_function
import os
import hashlib
import datetime
def FindDuplicateFiles(pth, minSize = 0, hashName = "md5"):
knownFiles = {}
for root, dirs, files in os.walk(pth):
for fina in files:
fullFina = os.path.join(root, fina)
isSymLink = os.path.isli... | let readdir_or_empty dir =
try Sys.readdir dir
with Sys_error e ->
prerr_endline ("Could not read dir " ^ dir ^ ": " ^ e);
[||]
let directory_walk root func =
let rec aux dir =
readdir_or_empty dir
|> Array.iter (fun filename ->
let path = Filename.concat dir filename in
let... |
Maintain the same structure and functionality when rewriting this code in OCaml. |
from sympy import isprime
def wagstaff(N):
pri, wcount = 1, 0
while wcount < N:
pri += 2
if isprime(pri):
wag = (2**pri + 1) // 3
if isprime(wag):
wcount += 1
print(f'{wcount: 3}: {pri: 5} => ',
f'{wag:,}' if ... | let is_prime n =
let rec test x =
let q = n / x in x > q || x * q <> n && n mod (x + 2) <> 0 && test (x + 6)
in if n < 5 then n lor 1 = 3 else n land 1 <> 0 && n mod 3 <> 0 && test 5
let is_wagstaff n =
let w = succ (1 lsl n) / 3 in
if is_prime n && is_prime w then Some (n, w) else None
let () =
let sho... |
Maintain the same structure and functionality when rewriting this code in OCaml. |
from sympy import isprime
def wagstaff(N):
pri, wcount = 1, 0
while wcount < N:
pri += 2
if isprime(pri):
wag = (2**pri + 1) // 3
if isprime(wag):
wcount += 1
print(f'{wcount: 3}: {pri: 5} => ',
f'{wag:,}' if ... | let is_prime n =
let rec test x =
let q = n / x in x > q || x * q <> n && n mod (x + 2) <> 0 && test (x + 6)
in if n < 5 then n lor 1 = 3 else n land 1 <> 0 && n mod 3 <> 0 && test 5
let is_wagstaff n =
let w = succ (1 lsl n) / 3 in
if is_prime n && is_prime w then Some (n, w) else None
let () =
let sho... |
Generate a OCaml translation of this Python snippet without changing its computational steps. |
from PIL import Image
im = Image.open("boxes_1.ppm")
im.save("boxes_1.jpg")
| let print_jpeg ~img ?(quality=96) () =
let cmd = Printf.sprintf "cjpeg -quality %d" quality in
let ic, oc = Unix.open_process cmd in
output_ppm ~img ~oc;
try
while true do
let c = input_char ic in
print_char c
done
with End_of_file -> ()
;;
|
Change the programming language of this snippet from Python to OCaml without modifying what it does. |
from __future__ import unicode_literals
import argparse
import fileinput
import os
import sys
from functools import partial
from itertools import count
from itertools import takewhile
ANSI_RESET = "\u001b[0m"
RED = (255, 0, 0)
GREEN = (0, 255, 0)
YELLOW = (255, 255, 0)
BLUE = (0, 0, 255)
MAGENTA = (255, 0, 255)... | #load "unix.cma"
#load "str.cma"
let colors = [|
((15, 0, 0), "31");
(( 0, 15, 0), "32");
((15, 15, 0), "33");
(( 0, 0, 15), "34");
((15, 0, 15), "35");
(( 0, 15, 15), "36");
|]
let square_dist (r1, g1, b1) (r2, g2, b2) =
let xd = r2 - r1 in
let yd = g2 - g1 in
let zd = b2 - b1 in
(xd * xd +... |
Can you help me rewrite this code in D instead of Go, keeping it the same logically? | 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... | import std.stdio, std.algorithm;
class AVLtree {
private Node* root;
private static struct Node {
private int key, balance;
private Node* left, right, parent;
this(in int k, Node* p) pure nothrow @safe @nogc {
key = k;
parent = p;
}
}
public bo... |
Convert this Go snippet to D and keep its semantics consistent. | 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) {
... | import std.conv;
import std.stdio;
alias index_t = uint;
alias integer = long;
class cf_t
{
protected bool terminated;
protected index_t m;
private integer[] memo;
public index_t maxTerms = 20;
this ()
{
terminated =... |
Change the following Go code into D without altering its purpose. | 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) {
... | import std.conv;
import std.stdio;
alias index_t = uint;
alias integer = long;
class cf_t
{
protected bool terminated;
protected index_t m;
private integer[] memo;
public index_t maxTerms = 20;
this ()
{
terminated =... |
Convert this Go block to D, preserving its control flow and logic. | var m = ` leading spaces
and blank lines`
| import std.stdio, std.string;
void main() {
q"[a string that you "don't" have to escape]"
.writeln;
q"EOS
This
is a multi-line
heredoc string
EOS".outdent.writeln;
}
|
Rewrite the snippet below in D so it works the same as the original Go code. | var m = ` leading spaces
and blank lines`
| import std.stdio, std.string;
void main() {
q"[a string that you "don't" have to escape]"
.writeln;
q"EOS
This
is a multi-line
heredoc string
EOS".outdent.writeln;
}
|
Convert this Go snippet to D and keep its semantics consistent. | 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 = ... | int i;
int* ip = &i;
|
Change the programming language of this snippet from Go to D without modifying what it does. | 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 =... | import std.stdio, std.string, std.random;
import core.stdc.stdlib: exit;
struct G2048 {
void gameLoop() {
addTile;
while (true) {
if (moved)
addTile;
drawBoard;
if (done)
break;
waitKey;
}
writeln(win ? ... |
Port the following code from Go to D 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... | import std.stdio, std.random;
enum nPlayers = 4, maxPoints = 100;
enum Moves { roll, hold }
abstract class Player {
public:
final void addCurrScore() pure nothrow {
current_score += round_score;
}
final int getCurrScore() const pure nothrow {
return current_score;
}
final int ge... |
Rewrite this program in D while keeping its functionality equivalent to the Go version. | 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... | import std.stdio, std.random;
enum nPlayers = 4, maxPoints = 100;
enum Moves { roll, hold }
abstract class Player {
public:
final void addCurrScore() pure nothrow {
current_score += round_score;
}
final int getCurrScore() const pure nothrow {
return current_score;
}
final int ge... |
Translate the given Go code snippet into D without altering its behavior. | 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... | import std.stdio, std.random, std.string, std.array, std.algorithm,
std.file, std.conv;
enum int cx = 4, cy = 2;
enum int cx2 = cx / 2, cy2 = cy / 2;
enum pathSymbol = '.';
struct V2 { int x, y; }
bool solveMaze(char[][] maze, in V2 s, in V2 end) pure nothrow @safe @nogc {
if (s == end)
return tru... |
Preserve the algorithm and functionality while converting the code from Go to D. | 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... | import std.stdio, std.math, std.algorithm, std.range, std.typecons;
auto mean(T)(in T[] xs) pure nothrow @nogc {
return xs.sum / xs.length;
}
auto stdDev(T)(in T[] xs) pure nothrow {
immutable m = xs.mean;
return sqrt(xs.map!(x => (x - m) ^^ 2).sum / xs.length);
}
alias TF = double function(in double, in... |
Port the provided Go code into D while preserving the original functionality. | 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... | import std.stdio, std.math, std.algorithm, std.range, std.typecons;
auto mean(T)(in T[] xs) pure nothrow @nogc {
return xs.sum / xs.length;
}
auto stdDev(T)(in T[] xs) pure nothrow {
immutable m = xs.mean;
return sqrt(xs.map!(x => (x - m) ^^ 2).sum / xs.length);
}
alias TF = double function(in double, in... |
Produce a language-to-language conversion: from Go to D, same semantics. | package main
import "fmt"
func main() {
for {
fmt.Printf("SPAM\n")
}
}
| import std.stdio;
void main() {
while (true)
writeln("SPAM");
}
|
Change the following Go code into D without altering its purpose. | package main
import (
"fmt"
"math"
"bytes"
"encoding/binary"
)
type testCase struct {
hashCode string
string
}
var testCases = []testCase{
{"d41d8cd98f00b204e9800998ecf8427e", ""},
{"0cc175b9c0f1b6a831c399e269772661", "a"},
{"900150983cd24fb0d6963f7d28e17f72", "abc"},
{"f96b69... | import std.bitmanip, core.stdc.string, std.conv, std.math, std.array,
std.string;
version (D_InlineAsm_X86) {} else {
static assert(false, "For X86 machine only.");
}
uint S(in uint n) pure nothrow @safe @nogc {
static immutable aux = [7u, 12, 17, 22, 5, 9, 14, 20, 4, 11,
1... |
Preserve the algorithm and functionality while converting the code from Go to D. | func assert(t bool, s string) {
if !t {
panic(s)
}
}
assert(c == 0, "some text here")
| import std.stdio, std.algorithm, std.math;
double averageOfAbsolutes(in int[] values) pure nothrow @safe @nogc
in {
assert(values.length > 0);
} out(result) {
assert(result >= 0);
} body {
return values.map!abs.sum / double(values.length);
}
struct Foo {
int x;
void inc() { x++; }
in... |
Transform the following Go implementation into D, maintaining the same output and logic. | func assert(t bool, s string) {
if !t {
panic(s)
}
}
assert(c == 0, "some text here")
| import std.stdio, std.algorithm, std.math;
double averageOfAbsolutes(in int[] values) pure nothrow @safe @nogc
in {
assert(values.length > 0);
} out(result) {
assert(result >= 0);
} body {
return values.map!abs.sum / double(values.length);
}
struct Foo {
int x;
void inc() { x++; }
in... |
Write the same algorithm in D as shown in this Go implementation. | 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()}}}
}
... | import std.stdio, std.array, std.string, std.datetime, std.traits;
struct HistoryVariable(T) {
static struct HistoryValue {
SysTime time;
T value;
void toString(scope void delegate(const(char)[]) output)const {
output(format("%s; %s", time, value));
... |
Convert this Go snippet to D and keep its semantics consistent. | func multiply(a, b float64) float64 {
return a * b
}
|
int multiply1(int a, int b) {
return a * b;
}
enum result = multiply1(2, 3);
int[multiply1(2, 4)] array;
T multiply2(T)(T a, T b) {
return a * b;
}
enum multiply3(int a, int b) = a * b;
pragma(msg, multiply3!(2, 3));
void main() {
import std.stdio;
writeln("2 * 3 = ", result);
}
|
Write a version of this Go function in D with identical behavior. | package main
import "fmt"
func isPrime(n int) bool {
if n == 1 {
return false
}
i := 2
for i*i <= n {
if n%i == 0 {
return false
}
i++
}
return true
}
func main() {
var final, pNum int
for i := 1; pNum < 10001; i++ {
if isPrime(i) {... | import std.stdio;
int isprime( int p ) {
int i;
if(p==2) return 1;
if(!(p%2)) return 0;
for(i=3; i*i<=p; i+=2) {
if(!(p%i)) return 0;
}
return 1;
}
int prime( int n ) {
if(n==1) return 2;
int p, pn=1;
for(p=3;pn<n;p+=2) {
if(isprime(p)) pn++;
}
... |
Maintain the same structure and functionality when rewriting this code in D. | package main
import "fmt"
func isPrime(n int) bool {
if n == 1 {
return false
}
i := 2
for i*i <= n {
if n%i == 0 {
return false
}
i++
}
return true
}
func main() {
var final, pNum int
for i := 1; pNum < 10001; i++ {
if isPrime(i) {... | import std.stdio;
int isprime( int p ) {
int i;
if(p==2) return 1;
if(!(p%2)) return 0;
for(i=3; i*i<=p; i+=2) {
if(!(p%i)) return 0;
}
return 1;
}
int prime( int n ) {
if(n==1) return 2;
int p, pn=1;
for(p=3;pn<n;p+=2) {
if(isprime(p)) pn++;
}
... |
Produce a language-to-language conversion: from Go to D, same semantics. | package main
import (
"fmt"
"strconv"
"strings"
)
func divByAll(num int, digits []byte) bool {
for _, digit := range digits {
if num%int(digit-'0') != 0 {
return false
}
}
return true
}
func main() {
magic := 9 * 8 * 7
high := 9876432 / magic * magic
fo... | import std.algorithm.iteration : filter, map;
import std.algorithm.searching : all;
import std.conv : to;
import std.range : iota;
import std.stdio : writeln;
bool chkDec(int num) {
int[int] set;
return num
.to!string
.map!(c => c.to!int - '0')
.all!(d => (d != 0) && (num % d == 0) && ... |
Rewrite this program in D while keeping its functionality equivalent to the Go version. | package main
import (
"fmt"
"strconv"
"strings"
)
func divByAll(num int, digits []byte) bool {
for _, digit := range digits {
if num%int(digit-'0') != 0 {
return false
}
}
return true
}
func main() {
magic := 9 * 8 * 7
high := 9876432 / magic * magic
fo... | import std.algorithm.iteration : filter, map;
import std.algorithm.searching : all;
import std.conv : to;
import std.range : iota;
import std.stdio : writeln;
bool chkDec(int num) {
int[int] set;
return num
.to!string
.map!(c => c.to!int - '0')
.all!(d => (d != 0) && (num % d == 0) && ... |
Generate an equivalent D version of this Go code. | 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][σ]
}
... | import std.algorithm, std.range, std.traits, permutations2,
permutations_by_swapping1;
auto prod(Range)(Range r) nothrow @safe @nogc {
return reduce!q{a * b}(ForeachType!Range(1), r);
}
T permanent(T)(in T[][] a) nothrow @safe
in {
assert(a.all!(row => row.length == a[0].length));
} body {
auto r =... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.