Instruction stringlengths 45 106 | input_code stringlengths 1 13.7k | output_code stringlengths 1 13.7k |
|---|---|---|
Generate an equivalent OCaml version of this C++ code. | #include <iostream>
#include <cmath>
#include <optional>
#include <vector>
using namespace std;
template <typename T>
auto operator>>(const optional<T>& monad, auto f)
{
if(!monad.has_value())
{
return optional<remove_reference_t<decltype(*f(*monad))>>();
}
return f(*monad)... | let bind opt func = match opt with
| Some x -> func x
| None -> None
let return x = Some x
|
Rewrite this program in OCaml while keeping its functionality equivalent to the C++ version. | #include <iostream>
#include <vector>
using namespace std;
template <typename T>
auto operator>>(const vector<T>& monad, auto f)
{
vector<remove_reference_t<decltype(f(monad.front()).front())>> result;
for(auto& item : monad)
{
const auto r = f(item);
resul... | let bind : 'a list -> ('a -> 'b list) -> 'b list =
fun l f -> List.flatten (List.map f l)
let return x = [x]
|
Produce a functionally identical OCaml code for the snippet given in C++. | #include <fstream>
#include <iostream>
#include <unordered_map>
#include <vector>
struct Textonym_Checker {
private:
int total;
int elements;
int textonyms;
int max_found;
std::vector<std::string> max_strings;
std::unordered_map<std::string, std::vector<std::string>> values;
int get_mappin... | 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 the snippet below in OCaml so it works the same as the original C++ code. | #include <iostream>
#include <string>
#include <windows.h>
using namespace std;
typedef unsigned char byte;
enum fieldValues : byte { OPEN, CLOSED = 10, MINE, UNKNOWN, FLAG, ERR };
class fieldData
{
public:
fieldData() : value( CLOSED ), open( false ) {}
byte value;
bool open, mine;
};
class game
{
publi... | 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... |
Rewrite this program in OCaml while keeping its functionality equivalent to the C++ version. | #include <iostream>
auto Zero = [](auto){ return [](auto x){ return x; }; };
auto True = [](auto a){ return [=](auto){ return a; }; };
auto False = [](auto){ return [](auto b){ return b; }; };
auto Successor(auto a) {
return [=](auto f) {
return [=](auto x) {
return a(f)(f(x));
};
... |
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 ... |
Generate a OCaml translation of this C++ snippet without changing its computational steps. | #include <iostream>
auto Zero = [](auto){ return [](auto x){ return x; }; };
auto True = [](auto a){ return [=](auto){ return a; }; };
auto False = [](auto){ return [](auto b){ return b; }; };
auto Successor(auto a) {
return [=](auto f) {
return [=](auto x) {
return a(f)(f(x));
};
... |
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 this C++ snippet to OCaml and keep its semantics consistent. | #include <iostream>
struct SpecialVariables
{
int i = 0;
SpecialVariables& operator++()
{
this->i++;
return *this;
}
};
int main()
{
SpecialVariables sv;
auto sv2 = ++sv;
std::cout << " svΒ :" << sv.i << "\n sv2:" << sv2.i << "\n... | 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
|
Translate the given C++ code snippet into OCaml without altering its behavior. | #include <cstdint>
#include <iomanip>
#include <iostream>
#include <sstream>
class ipv4_cidr {
public:
ipv4_cidr() {}
ipv4_cidr(std::uint32_t address, unsigned int mask_length)
: address_(address), mask_length_(mask_length) {}
std::uint32_t address() const {
return address_;
}
unsi... | 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 =
... |
Port the following code from C++ to OCaml with equivalent syntax and logic. | #include <cstdint>
#include <iomanip>
#include <iostream>
#include <sstream>
class ipv4_cidr {
public:
ipv4_cidr() {}
ipv4_cidr(std::uint32_t address, unsigned int mask_length)
: address_(address), mask_length_(mask_length) {}
std::uint32_t address() const {
return address_;
}
unsi... | 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 =
... |
Can you help me rewrite this code in OCaml instead of C++, keeping it the same logically? | #include <gmpxx.h>
#include <chrono>
using namespace std;
using namespace chrono;
void agm(mpf_class& rop1, mpf_class& rop2, const mpf_class& op1,
const mpf_class& op2)
{
rop1 = (op1 + op2) / 2;
rop2 = op1 * op2;
mpf_sqrt(rop2.get_mpf_t(), rop2.get_mpf_t());
}
int main(void)
{
auto st = ste... | 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 ... |
Preserve the algorithm and functionality while converting the code from C++ to OCaml. | #include <gmpxx.h>
#include <chrono>
using namespace std;
using namespace chrono;
void agm(mpf_class& rop1, mpf_class& rop2, const mpf_class& op1,
const mpf_class& op2)
{
rop1 = (op1 + op2) / 2;
rop2 = op1 * op2;
mpf_sqrt(rop2.get_mpf_t(), rop2.get_mpf_t());
}
int main(void)
{
auto st = ste... | 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 C++ to OCaml without modifying what it does. | #include <iostream>
#include <iomanip>
#include <cmath>
namespace Rosetta {
template <int N>
class GaussLegendreQuadrature {
public:
enum {eDEGREE = N};
template <typename Function>
double integrate(double a, double b, Function f) {
double p = (b - a) / 2... | 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 = ... |
Write the same code in OCaml as shown below in C++. | #include <ciso646>
#include <iostream>
#include <regex>
#include <sstream>
#include <string>
#include <unordered_map>
#include <utility>
#include <vector>
using std::vector;
using std::string;
#include <exception>
#include <stdexcept>
template <typename...Args> std::runtime_error error( Args...args )
{
return st... | 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'
| ... |
Change the following C++ code into OCaml without altering its purpose. | #include <list>
#include <algorithm>
#include <iostream>
class point {
public:
point( int a = 0, int b = 0 ) { x = a; y = b; }
bool operator ==( const point& o ) { return o.x == x && o.y == y; }
point operator +( const point& o ) { return point( o.x + x, o.y + y ); }
int x, y;
};
class map {
public:
... | 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 ... |
Produce a language-to-language conversion: from C++ to OCaml, same semantics. | #include <list>
#include <algorithm>
#include <iostream>
class point {
public:
point( int a = 0, int b = 0 ) { x = a; y = b; }
bool operator ==( const point& o ) { return o.x == x && o.y == y; }
point operator +( const point& o ) { return point( o.x + x, o.y + y ); }
int x, y;
};
class map {
public:
... | 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 ... |
Write the same algorithm in OCaml as shown in this C++ implementation. | #include <iostream>
#include <cmath>
#include <cassert>
using namespace std;
#define PI 3.14159265359
class Vector
{
public:
Vector(double ix, double iy, char mode)
{
if(mode=='a')
{
x=ix*cos(iy);
y=ix*sin(iy);
}
else
{
x=ix;
... | 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}... |
Maintain the same structure and functionality when rewriting this code in OCaml. | #include <cmath>
#include <iostream>
using namespace std;
class EllipticPoint
{
double m_x, m_y;
static constexpr double ZeroThreshold = 1e20;
static constexpr double B = 7;
void Double() noexcept
{
if(IsZero())
{
... |
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 ... |
Port the provided C++ code into OCaml while preserving the original functionality. | #include <cmath>
#include <iostream>
using namespace std;
class EllipticPoint
{
double m_x, m_y;
static constexpr double ZeroThreshold = 1e20;
static constexpr double B = 7;
void Double() noexcept
{
if(IsZero())
{
... |
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 ... |
Port the provided C++ code into OCaml while preserving the original functionality. | #include <iostream>
#include <string>
#include <vector>
#include <queue>
#include <regex>
#include <tuple>
#include <set>
#include <array>
using namespace std;
class Board
{
public:
vector<vector<char>> sData, dData;
int px, py;
Board(string b)
{
regex pattern("([^\\n]+)\\n?");
sregex_iterator end, it... | 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 ... |
Rewrite this program in OCaml while keeping its functionality equivalent to the C++ version. | #include <iomanip>
#include <iostream>
#include <gmpxx.h>
using big_int = mpz_class;
std::string to_string(const big_int& num, size_t n) {
std::string str = num.get_str();
size_t len = str.size();
if (len > n) {
str = str.substr(0, n / 2) + "..." + str.substr(len - n / 2);
str += " (";
... | 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... |
Convert this C++ block to OCaml, preserving its control flow and logic. | #include<iostream>
#include<string>
#include<boost/filesystem.hpp>
#include<boost/format.hpp>
#include<boost/iostreams/device/mapped_file.hpp>
#include<optional>
#include<algorithm>
#include<iterator>
#include<execution>
#include"dependencies/xxhash.hpp"
template<typename T, typename V, typename F>
size_t for_each_... | 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. | #include <gmpxx.h>
#include <primesieve.hpp>
#include <iostream>
using big_int = mpz_class;
std::string to_string(const big_int& num, size_t n) {
std::string str = num.get_str();
size_t len = str.size();
if (len > n) {
str = str.substr(0, n / 2) + "..." + str.substr(len - n / 2);
str += "... | 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... |
Write the same algorithm in OCaml as shown in this C++ implementation. | #include <gmpxx.h>
#include <primesieve.hpp>
#include <iostream>
using big_int = mpz_class;
std::string to_string(const big_int& num, size_t n) {
std::string str = num.get_str();
size_t len = str.size();
if (len > n) {
str = str.substr(0, n / 2) + "..." + str.substr(len - n / 2);
str += "... | 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... |
Translate the given Python code snippet into OCaml without altering its behavior. | list1 = [1, 2, 3, 4, 5, 6, 7, 8, 9]
list2 = [10, 11, 12, 13, 14, 15, 16, 17, 18]
list3 = [19, 20, 21, 22, 23, 24, 25, 26, 27]
print([
''.join(str(n) for n in z) for z
in zip(list1, list2, list3)
])
| let lists = [
["1"; "2"; "3"; "4"; "5"; "6"; "7"; "8"; "9"];
["10"; "11"; "12"; "13"; "14"; "15"; "16"; "17"; "18"];
["19"; "20"; "21"; "22"; "23"; "24"; "25"; "26"; "27"]]
let reduce f = function
| h :: t -> List.fold_left f h t
| _ -> invalid_arg "reduce"
let () =
reduce (List.map2 (^)) lists |> String.... |
Port the provided Python code into OCaml while preserving the original functionality. | list1 = [1, 2, 3, 4, 5, 6, 7, 8, 9]
list2 = [10, 11, 12, 13, 14, 15, 16, 17, 18]
list3 = [19, 20, 21, 22, 23, 24, 25, 26, 27]
print([
''.join(str(n) for n in z) for z
in zip(list1, list2, list3)
])
| let lists = [
["1"; "2"; "3"; "4"; "5"; "6"; "7"; "8"; "9"];
["10"; "11"; "12"; "13"; "14"; "15"; "16"; "17"; "18"];
["19"; "20"; "21"; "22"; "23"; "24"; "25"; "26"; "27"]]
let reduce f = function
| h :: t -> List.fold_left f h t
| _ -> invalid_arg "reduce"
let () =
reduce (List.map2 (^)) lists |> String.... |
Convert this Python block to OCaml, preserving its control flow and logic. | import math
print("working...")
limit1 = 6000
limit2 = 1000
oldSquare = 0
newSquare = 0
for n in range(limit1):
newSquare = n*n
if (newSquare - oldSquare > limit2):
print("Least number is = ", end = "");
print(int(math.sqrt(newSquare)))
break
oldSquare = n*n
print("done...")
print()
| let calculate x =
succ (succ x lsr 1)
let () =
Printf.printf "%u\n" (calculate 1000)
|
Produce a language-to-language conversion: from Python to OCaml, same semantics. | import math
print("working...")
limit1 = 6000
limit2 = 1000
oldSquare = 0
newSquare = 0
for n in range(limit1):
newSquare = n*n
if (newSquare - oldSquare > limit2):
print("Least number is = ", end = "");
print(int(math.sqrt(newSquare)))
break
oldSquare = n*n
print("done...")
print()
| let calculate x =
succ (succ x lsr 1)
let () =
Printf.printf "%u\n" (calculate 1000)
|
Write the same code in OCaml as shown below in Python. | from __future__ import annotations
import itertools
import random
from enum import Enum
from typing import Any
from typing import Tuple
import pygame as pg
from pygame import Color
from pygame import Rect
from pygame.surface import Surface
from pygame.sprite import AbstractGroup
from pygame.sprite import Group
f... |
open Sdl
let width, height = (640, 480)
type pos = int * int
type game_state = {
pos_snake: pos;
seg_snake: pos list;
dir_snake: [`left | `right | `up | `down];
pos_fruit: pos;
sleep_time: int;
game_over: bool;
}
let red = (255, 0, 0)
let blue = (0, 0, 255)
let green = (0, 255, 0)
let black = (0, 0,... |
Convert this Python block to OCaml, preserving its control flow and logic. | def setup():
size(600, 600)
background(0)
stroke(255)
drawTree(300, 550, 9)
def drawTree(x, y, depth):
fork_ang = radians(20)
base_len = 10
if depth > 0:
pushMatrix()
translate(x, y - baseLen * depth)
line(0, baseLen * depth, 0, 0)
rotate(fork_ang)
... | #directory "+cairo"
#load "bigarray.cma"
#load "cairo.cma"
let img_name = "/tmp/fractree.png"
let width = 480
let height = 640
let level = 9
let line_width = 4.0
let color = (1.0, 0.5, 0.0)
let pi = 4.0 *. atan 1.0
let angle_split = pi *. 0.12
let angle_rand = pi *. 0.12
let () =
Random.self_init();
let sur... |
Write the same algorithm in OCaml as shown in this Python implementation. | from random import choice
rules = {'rock': 'paper', 'scissors': 'rock', 'paper': 'scissors'}
previous = ['rock', 'paper', 'scissors']
while True:
human = input('\nchoose your weapon: ')
computer = rules[choice(previous)]
if human in ('quit', 'exit'): break
elif human in rules:
previous.app... | let pf = Printf.printf ;;
let looses a b = match a, b with
`R, `P -> true
| `P, `S -> true
| `S, `R -> true
| _, _ -> false ;;
let rec get_move () =
pf "[R]ock, [P]aper, [S]cisors [Q]uit? " ;
match String.uppercase (read_line ()) with
"P" -> `P
| "S" -> `S
| "R" -> `R
|... |
Translate this program into OCaml but keep the logic exactly as in Python. | from __future__ import division
from itertools import islice, count
from collections import Counter
from math import log10
from random import randint
expected = [log10(1+1/d) for d in range(1,10)]
def fib():
a,b = 1,1
while True:
yield a
a,b = b,a+b
def power_of_threes():
return (3**k fo... | open Num
let fib =
let rec fib_aux f0 f1 = function
| 0 -> f0
| 1 -> f1
| n -> fib_aux f1 (f1 +/ f0) (n - 1)
in
fib_aux (num_of_int 0) (num_of_int 1) ;;
let create_fibo_string = function n -> string_of_num (fib n) ;;
let rec range i j = if i > j then [] else i :: (range (i + 1) j)
let n_max = 1000 ... |
Generate a OCaml translation of this Python snippet without changing its computational steps. | from __future__ import division
from itertools import islice, count
from collections import Counter
from math import log10
from random import randint
expected = [log10(1+1/d) for d in range(1,10)]
def fib():
a,b = 1,1
while True:
yield a
a,b = b,a+b
def power_of_threes():
return (3**k fo... | open Num
let fib =
let rec fib_aux f0 f1 = function
| 0 -> f0
| 1 -> f1
| n -> fib_aux f1 (f1 +/ f0) (n - 1)
in
fib_aux (num_of_int 0) (num_of_int 1) ;;
let create_fibo_string = function n -> string_of_num (fib n) ;;
let rec range i j = if i > j then [] else i :: (range (i + 1) j)
let n_max = 1000 ... |
Produce a functionally identical OCaml code for the snippet given in Python. | from decimal import Decimal
import math
def h(n):
'Simple, reduced precision calculation'
return math.factorial(n) / (2 * math.log(2) ** (n + 1))
def h2(n):
'Extended precision Hickerson function'
return Decimal(math.factorial(n)) / (2 * Decimal(2).ln() ** (n + 1))
for n in range(18):
x = h2(... | local
fun log (n, k, last = sum, sum) = sum
| (n, k, last, sum) = log (n, k + 1, sum, sum + ( 1 / (k * n ^ k)))
| n = log (n, 1, 1, 0);
val ln2 = log 2
in
fun hickerson n = (fold (opt *,1) ` iota n) / (2 * ln2 ^ (n+1));
... |
Please provide an equivalent version of this Python code in OCaml. | from decimal import Decimal
import math
def h(n):
'Simple, reduced precision calculation'
return math.factorial(n) / (2 * math.log(2) ** (n + 1))
def h2(n):
'Extended precision Hickerson function'
return Decimal(math.factorial(n)) / (2 * Decimal(2).ln() ** (n + 1))
for n in range(18):
x = h2(... | local
fun log (n, k, last = sum, sum) = sum
| (n, k, last, sum) = log (n, k + 1, sum, sum + ( 1 / (k * n ^ k)))
| n = log (n, 1, 1, 0);
val ln2 = log 2
in
fun hickerson n = (fold (opt *,1) ` iota n) / (2 * ln2 ^ (n+1));
... |
Produce a language-to-language conversion: from Python to OCaml, same semantics. | def readconf(fn):
ret = {}
with file(fn) as fp:
for line in fp:
line = line.strip()
if not line or line.startswith('
boolval = True
if line.startswith(';'):
line = line.lstrip(';')
... | #use "topfind"
#require "inifiles"
open Inifiles
let print_field ini (label, field) =
try
let v = ini#getval "params" field in
Printf.printf "%s: %s\n" label v
with Invalid_element _ ->
Printf.printf "%s: not defined\n" label
let () =
let ini = new inifile "./conf.ini" in
let lst = [
"Full nam... |
Convert this Python block to OCaml, preserving its control flow and logic. | def is_prime(n: int) -> bool:
if n <= 3:
return n > 1
if n % 2 == 0 or n % 3 == 0:
return False
i = 5
while i ** 2 <= n:
if n % i == 0 or n % (i + 2) == 0:
return False
i += 6
return True
def digit_sum(n: int) -> int:
sum = 0
while n > 0:
... | let rec digit_sum n =
if n < 10 then n else n mod 10 + digit_sum (n / 10)
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_additive_prime n =
is_prime n && is_prime ... |
Generate an equivalent OCaml version of this Python code. | >>> dog = 'Benjamin'; Dog = 'Samba'; DOG = 'Bernie'
>>> print ('The three dogs are named ',dog,', ',Dog,', and ',DOG)
The three dogs are named Benjamin , Samba , and Bernie
>>>
| let () =
let dog = "Benjamin" in
let dOG = "Samba" in
let dOg = "Bernie" in
Printf.printf "The three dogs are named %s, %s and %s.\n" dog dOG dOg
|
Generate an equivalent OCaml version of this Python code. | command_table_text = \
user_words = "riG rePEAT copies put mo rest types fup. 6 poweRin"
def find_abbreviations_length(command_table_text):
command_table = dict()
for word in command_table_text.split():
abbr_len = sum(1 for c in word if c.isupper())
if abbr_len == 0:
... | let cmds = "\
Add ALTer BAckup Bottom CAppend Change SCHANGE CInsert CLAst COMPress COpy
COUnt COVerlay CURsor DELete CDelete Down DUPlicate Xedit EXPand EXTract Find
NFind NFINDUp NFUp CFind FINdup FUp FOrward GET Help HEXType Input POWerinput
Join SPlit SPLTJOIN LOAD Locate CLocate LOWercase UPPercase ... |
Translate this program into OCaml but keep the logic exactly as in Python. | command_table_text = \
user_words = "riG rePEAT copies put mo rest types fup. 6 poweRin"
def find_abbreviations_length(command_table_text):
command_table = dict()
for word in command_table_text.split():
abbr_len = sum(1 for c in word if c.isupper())
if abbr_len == 0:
... | let cmds = "\
Add ALTer BAckup Bottom CAppend Change SCHANGE CInsert CLAst COMPress COpy
COUnt COVerlay CURsor DELete CDelete Down DUPlicate Xedit EXPand EXTract Find
NFind NFINDUp NFUp CFind FINdup FUp FOrward GET Help HEXType Input POWerinput
Join SPlit SPLTJOIN LOAD Locate CLocate LOWercase UPPercase ... |
Ensure the translated OCaml code behaves exactly like the original Python snippet. | >>> data = [1, 4, 5, 3, -6, 3, 7, 10, -2, -5, 7, 5, 9, -3, 7]
>>> def stoogesort(L, i=0, j=None):
if j is None:
j = len(L) - 1
if L[j] < L[i]:
L[i], L[j] = L[j], L[i]
if j - i > 1:
t = (j - i + 1) // 3
stoogesort(L, i , j-t)
stoogesort(L, i+t, j )
stoogesort(L, i , j-t)
return L
>>> stoogesort(data)... | let swap ar i j =
let tmp = ar.(i) in
ar.(i) <- ar.(j);
ar.(j) <- tmp
let stoogesort ar =
let rec aux i j =
if ar.(j) < ar.(i) then
swap ar i j
else if j - i > 1 then begin
let t = (j - i + 1) / 3 in
aux (i) (j-t);
aux (i+t) (j);
aux (i) (j-t);
end
in
aux 0 (Array.... |
Rewrite the snippet below in OCaml so it works the same as the original Python code. | def truncate_file(name, length):
if not os.path.isfile(name):
return False
if length >= os.path.getsize(name):
return False
with open(name, 'ab') as f:
f.truncate(length)
return True
| val truncate : string -> int -> unit
|
Preserve the algorithm and functionality while converting the code from Python to OCaml. | def truncate_file(name, length):
if not os.path.isfile(name):
return False
if length >= os.path.getsize(name):
return False
with open(name, 'ab') as f:
f.truncate(length)
return True
| val truncate : string -> int -> unit
|
Translate the given Python code snippet into OCaml without altering its behavior. | def shell(seq):
inc = len(seq) // 2
while inc:
for i, el in enumerate(seq[inc:], inc):
while i >= inc and seq[i - inc] > el:
seq[i] = seq[i - inc]
i -= inc
seq[i] = el
inc = 1 if inc == 2 else inc * 5 // 11
| let shellsort a =
let len = Array.length a in
let incSequence = [| 412771; 165103; 66041; 26417; 10567;
4231; 1693; 673; 269; 107; 43; 17; 7; 3; 1 |] in
Array.iter (fun increment ->
if (increment * 2) <= len then
for i = increment to pred len do
let temp = a.(i) in
... |
Translate the given Python code snippet into OCaml without altering its behavior. | with open('xxx.txt') as f:
for i, line in enumerate(f):
if i == 6:
break
else:
print('Not 7 lines in file')
line = None
| let input_line_opt ic =
try Some (input_line ic)
with End_of_file -> None
let nth_line n filename =
let ic = open_in filename in
let rec aux i =
match input_line_opt ic with
| Some line ->
if i = n then begin
close_in ic;
(line)
end else aux (succ i)
| None ->
... |
Please provide an equivalent version of this Python code in OCaml. | with open('xxx.txt') as f:
for i, line in enumerate(f):
if i == 6:
break
else:
print('Not 7 lines in file')
line = None
| let input_line_opt ic =
try Some (input_line ic)
with End_of_file -> None
let nth_line n filename =
let ic = open_in filename in
let rec aux i =
match input_line_opt ic with
| Some line ->
if i = n then begin
close_in ic;
(line)
end else aux (succ i)
| None ->
... |
Transform the following Python implementation into OCaml, maintaining the same output and logic. |
def isPrime(n):
for i in range(2, int(n**0.5) + 1):
if n % i == 0:
return False
return True
def isBackPrime(n):
if not isPrime(n):
return False
m = 0
while n:
m *= 10
m += n % 10
n //= 10
return isPrime(m)
if __name__ == '__main__':... | let int_reverse =
let rec loop m n =
if n < 10 then m + n else loop ((m + n mod 10) * 10) (n / 10)
in loop 0
let is_prime n =
let not_divisible x = n mod x <> 0 in
seq_primes |> Seq.take_while (fun x -> x * x <= n) |> Seq.for_all not_divisible
let () =
seq_primes |> Seq.filter (fun p -> is_prime (int_re... |
Write a version of this Python function in OCaml with identical behavior. |
def isPrime(n):
for i in range(2, int(n**0.5) + 1):
if n % i == 0:
return False
return True
def isBackPrime(n):
if not isPrime(n):
return False
m = 0
while n:
m *= 10
m += n % 10
n //= 10
return isPrime(m)
if __name__ == '__main__':... | let int_reverse =
let rec loop m n =
if n < 10 then m + n else loop ((m + n mod 10) * 10) (n / 10)
in loop 0
let is_prime n =
let not_divisible x = n mod x <> 0 in
seq_primes |> Seq.take_while (fun x -> x * x <= n) |> Seq.for_all not_divisible
let () =
seq_primes |> Seq.filter (fun p -> is_prime (int_re... |
Maintain the same structure and functionality when rewriting this code in OCaml. | import urllib
s = 'http://foo/bar/'
s = urllib.quote(s)
| $ ocaml
# #use "topfind";;
# #require "netstring";;
# Netencoding.Url.encode "http://foo bar/" ;;
- : string = "http%3A%2F%2Ffoo+bar%2F"
|
Port the provided Python code into OCaml while preserving the original functionality. | import urllib
s = 'http://foo/bar/'
s = urllib.quote(s)
| $ ocaml
# #use "topfind";;
# #require "netstring";;
# Netencoding.Url.encode "http://foo bar/" ;;
- : string = "http%3A%2F%2Ffoo+bar%2F"
|
Port the provided Python code into OCaml while preserving the original functionality. | >>> def printtable(data):
for row in data:
print ' '.join('%-5s' % ('"%s"' % cell) for cell in row)
>>> import operator
>>> def sorttable(table, ordering=None, column=0, reverse=False):
return sorted(table, cmp=ordering, key=operator.itemgetter(column), reverse=reverse)
>>> data = [["a", "b",... | let sort_table ?(ordering = compare) ?(column = 0) ?(reverse = false) table =
let cmp x y = ordering (List.nth x column) (List.nth y column) * (if reverse then -1 else 1) in
List.sort cmp table
|
Ensure the translated OCaml code behaves exactly like the original Python snippet. | Python 3.2.2 (default, Sep 4 2011, 09:51:08) [MSC v.1500 32 bit (Intel)] on win32
Type "copyright", "credits" or "license()" for more information.
>>> def f(x): return abs(x) ** 0.5 + 5 * x**3
>>> print(', '.join('%s:%s' % (x, v if v<=400 else "TOO LARGE!")
for x,v in ((y, f(float(y))) for y in input('\nn... | let f x = sqrt x +. 5.0 *. (x ** 3.0)
let p x = x < 400.0
let () =
print_endline "Please enter 11 Numbers:";
let lst = Array.to_list (Array.init 11 (fun _ -> read_float ())) in
List.iter (fun x ->
let res = f x in
if p res
then Printf.printf "f(%g) = %g\n%!" x res
else Printf.eprintf "f(%g)Β :: Ov... |
Generate an equivalent OCaml version of this Python code. | import threading
from time import sleep
res = 2
sema = threading.Semaphore(res)
class res_thread(threading.Thread):
def run(self):
global res
n = self.getName()
for i in range(1, 4):
sema.acquire()
res = res - 1
p... | let m = Mutex.create() in
Mutex.lock m;
if (Mutex.try_lock m)
then ...
else ...
Mutex.unlock m;
|
Translate this program into OCaml but keep the logic exactly as in Python. | from sys import stdin, stdout
def char_in(): return stdin.read(1)
def char_out(c): stdout.write(c)
def odd(prev = lambda: None):
a = char_in()
if not a.isalpha():
prev()
char_out(a)
return a != '.'
def clos():
char_out(a)
prev()
return odd(clos)
def even():
while True:
c = char_in()
char_out(c... | let is_alpha c =
c >= 'a' && c <= 'z' ||
c >= 'A' && c <= 'Z'
let rec odd () =
let c = input_char stdin in
if is_alpha c
then (let e = odd () in print_char c; e)
else (c)
let rec even () =
let c = input_char stdin in
if is_alpha c
then (print_char c; even ())
else print_char c
let rev_odd_words (... |
Generate a OCaml translation of this Python snippet without changing its computational steps. | mask64 = (1 << 64) - 1
mask32 = (1 << 32) - 1
CONST = 6364136223846793005
class PCG32():
def __init__(self, seed_state=None, seed_sequence=None):
if all(type(x) == int for x in (seed_state, seed_sequence)):
self.seed(seed_state, seed_sequence)
else:
self.state = self.i... | let (>>) = Int64.shift_right_logical
let int32_bound n x =
Int64.(to_int ((mul (logand (of_int32 x) 0xffffffffL) (of_int n)) >> 32))
let int32_rotate_right x n =
Int32.(logor (shift_left x (-n land 31)) (shift_right_logical x n))
let pcg32_next inc st =
Int64.(add (mul st 0x5851f42d4c957f2dL) inc)
let pcg32_o... |
Please provide an equivalent version of this Python code in OCaml. | from ctypes import Structure, c_int
rs232_9pin = "_0 CD RD TD DTR SG DSR RTS CTS RI".split()
rs232_25pin = ( "_0 PG TD RD RTS CTS DSR SG CD pos neg"
"_11 SCD SCS STD TC SRD RC"
"_18 SRS DTR SQD RI DRS XTC" ).split()
class RS232_9pin(Structure):
_fields_ = [(__, c_int, 1) fo... | open ExtLib
class rs232_data = object
val d = BitSet.create 9
method carrier_detect = BitSet.is_set d 0
method received_data = BitSet.is_set d 1
method transmitted_data = BitSet.is_set d 2
method data_terminal_ready = BitSet.is_set d 3
method signal_ground = BitSet.is_set d 4
method d... |
Can you help me rewrite this code in OCaml instead of Python, keeping it the same logically? |
from itertools import dropwhile, takewhile
def nnPeers(n):
def p(x):
return n == x
def go(xs):
fromFirstMatch = list(dropwhile(
lambda v: not p(v),
xs
))
ns = list(takewhile(p, fromFirstMatch))
rest = fromFirstMatch[len(ns):]
re... | let has_adjacent n x =
let rec loop c = function
| h :: t when h = x -> loop (succ c) t
| _ :: t -> c = n || loop 0 t
| _ -> c = n
in loop 0
let list = [
[9; 3; 3; 3; 2; 1; 7; 8; 5];
[5; 2; 9; 3; 3; 7; 8; 4; 1];
[1; 4; 3; 6; 7; 3; 8; 3; 2];
[1; 2; 3; 4; 5; 6; 7; 8; 9];
[4; 6; 8; 7; 2; 3; 3; 3... |
Generate an equivalent OCaml version of this Python code. |
from functools import reduce
from operator import mul
def p(n):
digits = [int(c) for c in str(n)]
return not 0 in digits and (
0 != (n % reduce(mul, digits, 1))
) and all(0 == n % d for d in digits)
def main():
xs = [
str(n) for n in range(1, 1000)
if p(n)
... | let test b x =
let rec loop m n =
if n < b
then x mod n = 0 && x mod (m * n) > 0
else let d = n mod b in d > 0 && x mod d = 0 && loop (m * d) (n / b)
in loop 1 x
let () =
Seq.ints 1 |> Seq.take 999 |> Seq.filter (test 10)
|> Seq.iter (Printf.printf " %u") |> print_newline
|
Change the following Python code into OCaml without altering its purpose. | def rotate(list, n):
for _ in range(n):
list.append(list.pop(0))
return list
def rotate(list, n):
k = (len(list) + n) % len(list)
return list[k::] + list[:k:]
list = [1,2,3,4,5,6,7,8,9]
print(list, " => ", rotate(list, 3))
| # let rec rotate n = function
| h :: (_ :: _ as t) when n > 0 -> rotate (pred n) (t @ [h])
| l -> l
;;
val rotate : int -> 'a list -> 'a list = <fun>
# rotate 3 [1; 2; 3; 4; 5; 6; 7; 8; 9] ;;
- : int list = [4; 5; 6; 7; 8; 9; 1; 2; 3]
|
Maintain the same structure and functionality when rewriting this code in OCaml. | col = 0
for i in range(100000):
if set(str(i)) == set(hex(i)[2:]):
col += 1
print("{:7}".format(i), end='\n'[:col % 10 == 0])
print()
| module CSet = Set.Make(struct
type t = char
let compare = compare
end)
let str2cset str = CSet.add_seq (String.to_seq str) CSet.empty
let has_same_digits n =
let deci = Format.sprintf "%d" n in
let hexa = Format.sprintf "%x" n in
CSet.equal (str2cset deci) (str2cset hexa)
let rec list_similar ?(acc=[]) ... |
Rewrite the snippet below in OCaml so it works the same as the original Python code. | from itertools import product
print(sorted(set(a**b for (a,b) in product(range(2,6), range(2,6)))))
| module IntSet = Set.Make(Int)
let pow x =
let rec aux acc b = function
| 0 -> acc
| y -> aux (if y land 1 = 0 then acc else acc * b) (b * b) (y lsr 1)
in
aux 1 x
let distinct_powers first count =
let sq = Seq.(take count (ints first)) in
IntSet.of_seq (Seq.map_product pow sq sq)
let () = distinct... |
Ensure the translated OCaml code behaves exactly like the original Python snippet. | class NG:
def __init__(self, a1, a, b1, b):
self.a1, self.a, self.b1, self.b = a1, a, b1, b
def ingress(self, n):
self.a, self.a1 = self.a1, self.a + self.a1 * n
self.b, self.b1 = self.b1, self.b + self.b1 * n
@property
def needterm(self):
return (self.b == 0 or self.b1 == 0) or not self.a//se... | module CF =
struct
type record_t =
{
terminated : bool;
m : int;
memo : int Array.t;
gen : unit -> int option;
}
type t = record_t ref
let make gen =
ref { terminated = false;
m = 0;
memo = ... |
Write the same code in OCaml as shown below in Python. | class NG:
def __init__(self, a1, a, b1, b):
self.a1, self.a, self.b1, self.b = a1, a, b1, b
def ingress(self, n):
self.a, self.a1 = self.a1, self.a + self.a1 * n
self.b, self.b1 = self.b1, self.b + self.b1 * n
@property
def needterm(self):
return (self.b == 0 or self.b1 == 0) or not self.a//se... | module CF =
struct
type record_t =
{
terminated : bool;
m : int;
memo : int Array.t;
gen : unit -> int option;
}
type t = record_t ref
let make gen =
ref { terminated = false;
m = 0;
memo = ... |
Produce a language-to-language conversion: from Python to OCaml, same semantics. | print()
| print_string {whatever|
'hahah', `this`
<is>
\a\
"Heredoc" ${example}
in OCaml
|whatever}
;;
|
Transform the following Python implementation into OCaml, maintaining the same output and logic. | print()
| print_string {whatever|
'hahah', `this`
<is>
\a\
"Heredoc" ${example}
in OCaml
|whatever}
;;
|
Maintain the same structure and functionality when rewriting this code in OCaml. | from itertools import product
from collections import defaultdict
class Sandpile():
def __init__(self, gridtext):
array = [int(x) for x in gridtext.strip().split()]
self.grid = defaultdict(int,
{(i //3, i % 3): x
for i, x in enumera... |
module Make =
functor (M : sig val m : int val n : int end)
-> struct
type t = { grid : int array array ; unstable : ((int*int),unit) Hashtbl.t }
let make () = { grid = Array.init M.m (fun _ -> Array.make M.n 0); unstable = Hashtbl.create 10 }
let print {grid=grid} =
for i = 0... |
Port the provided Python code into OCaml while preserving the original functionality. | from itertools import product
from collections import defaultdict
class Sandpile():
def __init__(self, gridtext):
array = [int(x) for x in gridtext.strip().split()]
self.grid = defaultdict(int,
{(i //3, i % 3): x
for i, x in enumera... |
module Make =
functor (M : sig val m : int val n : int end)
-> struct
type t = { grid : int array array ; unstable : ((int*int),unit) Hashtbl.t }
let make () = { grid = Array.init M.m (fun _ -> Array.make M.n 0); unstable = Hashtbl.create 10 }
let print {grid=grid} =
for i = 0... |
Write a version of this Python function in OCaml with identical behavior. |
def p(n):
return 9 < n and (9 < n % 16 or p(n // 16))
def main():
xs = [
str(n) for n in range(1, 1 + 500)
if p(n)
]
print(f'{len(xs)} matches for the predicate:\n')
print(
table(6)(xs)
)
def chunksOf(n):
def go(xs):
return (
... | let rec has_xdigit n =
n land 15 > 9 || n > 15 && has_xdigit (n lsr 4)
let () =
Seq.(ints 1 |> take 500 |> filter has_xdigit |> map string_of_int)
|> List.of_seq |> String.concat " " |> print_endline
|
Convert this Python block to OCaml, preserving its control flow and logic. |
def p(n):
return 9 < n and (9 < n % 16 or p(n // 16))
def main():
xs = [
str(n) for n in range(1, 1 + 500)
if p(n)
]
print(f'{len(xs)} matches for the predicate:\n')
print(
table(6)(xs)
)
def chunksOf(n):
def go(xs):
return (
... | let rec has_xdigit n =
n land 15 > 9 || n > 15 && has_xdigit (n lsr 4)
let () =
Seq.(ints 1 |> take 500 |> filter has_xdigit |> map string_of_int)
|> List.of_seq |> String.concat " " |> print_endline
|
Write the same algorithm in OCaml as shown in this Python implementation. | var num = 12
var pointer = ptr(num)
print pointer
@unsafe
pointer.addr = 0xFFFE
| let address_of (x:'a) : nativeint =
if Obj.is_block (Obj.repr x) then
Nativeint.shift_left (Nativeint.of_int (Obj.magic x)) 1
else
invalid_arg "Can only find address of boxed values.";;
let () =
let a = 3.14 in
Printf.printf "%nx\n" (address_of a);;
let b = ref 42 in
Printf.printf "%nx\n" (address... |
Maintain the same structure and functionality when rewriting this code in OCaml. |
import curses
from random import randrange, choice
from collections import defaultdict
letter_codes = [ord(ch) for ch in 'WASDRQwasdrq']
actions = ['Up', 'Left', 'Down', 'Right', 'Restart', 'Exit']
actions_dict = dict(zip(letter_codes, actions * 2))
def get_user_action(keyboard):
char = "N"
while char not in... | let list_make x v =
let rec aux acc i =
if i <= 0 then acc else aux (v::acc) (i-1)
in
aux [] x
let pad_right n line =
let len = List.length line in
let x = n - len in
line @ (list_make x 0)
let _move_left line =
let n = List.length line in
let line = List.filter ((<>) 0) line in
let rec aux ac... |
Please provide an equivalent version of this Python code in OCaml. | import sys
HIST = {}
def trace(frame, event, arg):
for name,val in frame.f_locals.items():
if name not in HIST:
HIST[name] = []
else:
if HIST[name][-1] is val:
continue
HIST[name].append(val)
return trace
def undo(name):
HIST[name].pop(-1)
... | open Stack
module H = Stack
let show_entry e =
Printf.printf "History entry: %5d\n" e
let () =
let hs = H.create() in
H.push 111 hs ;
H.push 4 hs ;
H.push 42 hs ;
H.iter show_entry hs;
hs |> H.pop |> Printf.printf "%d\n";
hs |> H.pop |> Printf.printf "%d\n";
hs |> H.pop |> Printf.printf "%d\n"
|
Transform the following Python implementation into OCaml, maintaining the same output and logic. |
import sys
if len(sys.argv)!=2:
print("UsageΒ : python " + sys.argv[0] + " <filename>")
exit()
dataFile = open(sys.argv[1],"r")
fileData = dataFile.read().split('\n')
dataFile.close()
[print(i) for i in fileData[::-1]]
| let rec read_lines_reverse lst =
match read_line () with
| line -> read_lines_reverse (line :: lst)
| exception End_of_file -> lst
let () = read_lines_reverse [] |> List.iter print_endline
|
Translate the given Python code snippet into OCaml without altering its behavior. | def multiply(x, y):
return x * y
| let int_multiply x y = x * y
let float_multiply x y = x *. y
|
Change the programming language of this snippet from Python to OCaml without modifying what it does. |
from math import floor, pow
def isPrime(n):
for i in range(2, int(n**0.5) + 1):
if n % i == 0:
return False
return True
def odd(n):
return n and 1 != 0
def jacobsthal(n):
return floor((pow(2,n)+odd(n))/3)
def jacobsthal_lucas(n):
return int(pow(2,n)+pow(-1,n))
d... | 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 land 2 <> 0
else n land 1 <> 0 && n mod 3 <> 0 && test 5
let seq_jacobsthal =
let rec next b a () = Seq.Cons (a, next (a + a + b) b) in
next 1
let seq_jacobsthal_oblong =
let rec ne... |
Rewrite the snippet below in OCaml so it works the same as the original Python code. |
from math import floor, pow
def isPrime(n):
for i in range(2, int(n**0.5) + 1):
if n % i == 0:
return False
return True
def odd(n):
return n and 1 != 0
def jacobsthal(n):
return floor((pow(2,n)+odd(n))/3)
def jacobsthal_lucas(n):
return int(pow(2,n)+pow(-1,n))
d... | 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 land 2 <> 0
else n land 1 <> 0 && n mod 3 <> 0 && test 5
let seq_jacobsthal =
let rec next b a () = Seq.Cons (a, next (a + a + b) b) in
next 1
let seq_jacobsthal_oblong =
let rec ne... |
Produce a functionally identical OCaml code for the snippet given in Python. |
def isPrime(n):
for i in range(2, int(n**0.5) + 1):
if n % i == 0:
return False
return True
def prime(n: int) -> int:
if n == 1:
return 2
p = 3
pn = 1
while pn < n:
if isPrime(p):
pn += 1
p += 2
return p-2
if __name__ == '__... | let () =
seq_primes |> Seq.drop 10000 |> Seq.take 1 |> Seq.iter (Printf.printf "%u\n")
|
Translate the given Python code snippet into OCaml without altering its behavior. |
def isPrime(n):
for i in range(2, int(n**0.5) + 1):
if n % i == 0:
return False
return True
def prime(n: int) -> int:
if n == 1:
return 2
p = 3
pn = 1
while pn < n:
if isPrime(p):
pn += 1
p += 2
return p-2
if __name__ == '__... | let () =
seq_primes |> Seq.drop 10000 |> Seq.take 1 |> Seq.iter (Printf.printf "%u\n")
|
Generate an equivalent OCaml version of this Python code. | import os
def get_windows_terminal():
from ctypes import windll, create_string_buffer
h = windll.kernel32.GetStdHandle(-12)
csbi = create_string_buffer(22)
res = windll.kernel32.GetConsoleScreenBufferInfo(h, csbi)
if not res: return 80, 25
import struct
(bufx, bufy, curx, cury, watt... | $ ocaml unix.cma -I +ANSITerminal ANSITerminal.cma
# let width, height = ANSITerminal.size () ;;
val width : int = 126
val height : int = 47
|
Port the provided Python code into OCaml while preserving the original functionality. | from itertools import count, islice
from math import isqrt
def is_deceptive(n):
if n & 1 and n % 3 and n % 5 and pow(10, n - 1, n) == 1:
for d in range(7, isqrt(n) + 1, 6):
if not (n % d and n % (d + 4)): return True
return False
print(*islice(filter(is_deceptive, count()), 100))
| let modpow m =
let rec loop p b e =
if e land 1 = 0
then if e = 0 then p else loop p (b * b mod m) (e lsr 1)
else loop (p * b mod m) (b * b mod m) (e lsr 1)
in loop 1
let is_deceptive n =
let rec loop x =
x * x <= n && (n mod x = 0 || n mod (x + 4) = 0 || loop (x + 6))
in
n land 1 <> 0 && n m... |
Convert the following code from Python to OCaml, ensuring the logic remains intact. | from itertools import count, islice
from math import isqrt
def is_deceptive(n):
if n & 1 and n % 3 and n % 5 and pow(10, n - 1, n) == 1:
for d in range(7, isqrt(n) + 1, 6):
if not (n % d and n % (d + 4)): return True
return False
print(*islice(filter(is_deceptive, count()), 100))
| let modpow m =
let rec loop p b e =
if e land 1 = 0
then if e = 0 then p else loop p (b * b mod m) (e lsr 1)
else loop (p * b mod m) (b * b mod m) (e lsr 1)
in loop 1
let is_deceptive n =
let rec loop x =
x * x <= n && (n mod x = 0 || n mod (x + 4) = 0 || loop (x + 6))
in
n land 1 <> 0 && n m... |
Write the same algorithm in OCaml as shown in this Python implementation. | >>> from random import randrange
>>> def sattoloCycle(items):
for i in range(len(items) - 1, 0, -1):
j = randrange(i)
items[j], items[i] = items[i], items[j]
>>>
>>> for _ in range(10):
lst = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
sattoloCycle(lst)
print(lst)
[5, 8, 1, 2, 6, 4, 3, 9, 10, 7]
[5, 9, 8, 10, 4, ... | let sattolo_cycle arr =
for i = Array.length arr - 1 downto 1 do
let j = Random.int i in
let temp = arr.(i) in
arr.(i) <- arr.(j);
arr.(j) <- temp
done
|
Translate the given Python code snippet into OCaml without altering its behavior. | >>> from random import randrange
>>> def sattoloCycle(items):
for i in range(len(items) - 1, 0, -1):
j = randrange(i)
items[j], items[i] = items[i], items[j]
>>>
>>> for _ in range(10):
lst = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
sattoloCycle(lst)
print(lst)
[5, 8, 1, 2, 6, 4, 3, 9, 10, 7]
[5, 9, 8, 10, 4, ... | let sattolo_cycle arr =
for i = Array.length arr - 1 downto 1 do
let j = Random.int i in
let temp = arr.(i) in
arr.(i) <- arr.(j);
arr.(j) <- temp
done
|
Please provide an equivalent version of this Python code in OCaml. | >>> Y = lambda f: (lambda x: x(x))(lambda y: f(lambda *args: y(y)(*args)))
>>> fac = lambda f: lambda n: (1 if n<2 else n*f(n-1))
>>> [ Y(fac)(i) for i in range(10) ]
[1, 1, 2, 6, 24, 120, 720, 5040, 40320, 362880]
>>> fib = lambda f: lambda n: 0 if n == 0 else (1 if n == 1 else f(n-1) + f(n-2))
>>> [ Y(fib)(i) for i i... | let fix f g = (fun x a -> f (x x) a) (fun x a -> f (x x) a) g
|
Change the following Python code into OCaml without altering its purpose. | fact = [1]
for n in range(1, 12):
fact.append(fact[n-1] * n)
for b in range(9, 12+1):
print(f"The factorions for base {b} are:")
for i in range(1, 1500000):
fact_sum = 0
j = i
while j > 0:
d = j % b
fact_sum += fact[d]
j = j//b
if fact_su... | let () =
let fact = Array.make 12 0 in
fact.(0) <- 1;
for n = 1 to pred 12 do
fact.(n) <- fact.(n-1) * n;
done;
for b = 9 to 12 do
Printf.printf "The factorions for base %d are:\n" b;
for i = 1 to pred 1_500_000 do
let sum = ref 0 in
let j = ref i in
while !j > 0 do
l... |
Write the same code in OCaml as shown below in Python. | fact = [1]
for n in range(1, 12):
fact.append(fact[n-1] * n)
for b in range(9, 12+1):
print(f"The factorions for base {b} are:")
for i in range(1, 1500000):
fact_sum = 0
j = i
while j > 0:
d = j % b
fact_sum += fact[d]
j = j//b
if fact_su... | let () =
let fact = Array.make 12 0 in
fact.(0) <- 1;
for n = 1 to pred 12 do
fact.(n) <- fact.(n-1) * n;
done;
for b = 9 to 12 do
Printf.printf "The factorions for base %d are:\n" b;
for i = 1 to pred 1_500_000 do
let sum = ref 0 in
let j = ref i in
while !j > 0 do
l... |
Translate the given Python code snippet into OCaml without altering its behavior. | def _insort_right(a, x, q):
lo, hi = 0, len(a)
while lo < hi:
mid = (lo+hi)//2
q += 1
less = input(f"{q:2}: IS {x:>6} LESS-THAN {a[mid]:>6}Β ? y/n: ").strip().lower() == 'y'
if less: hi = mid
else: lo = mid+1
a.insert(lo, x)
return q
def order(items):
or... | let () =
let count = ref 0 in
let mycmp s1 s2 = (
incr count;
Printf.printf "(%d) Is %s <, ==, or > %s? Answer -1, 0, or 1: " (!count) s1 s2;
read_int ()
) in
let items = ["violet"; "red"; "green"; "indigo"; "blue"; "yellow"; "orange"] in
let sorted = List.sort mycmp items in
List.iter (Printf.p... |
Produce a functionally identical OCaml code for the snippet given in Python. |
from itertools import zip_longest
def beadsort(l):
return list(map(sum, zip_longest(*[[1] * e for e in l], fillvalue=0)))
print(beadsort([5,3,1,7,4,1,1]))
| let rec columns l =
match List.filter ((<>) []) l with
[] -> []
| l -> List.map List.hd l :: columns (List.map List.tl l)
let replicate n x = Array.to_list (Array.make n x)
let bead_sort l =
List.map List.length (columns (columns (List.map (fun e -> replicate e 1) l)))
|
Rewrite this program in OCaml while keeping its functionality equivalent to the Python version. |
import sys
print " ".join(sys.argv[1:])
| #! /usr/bin/env ocaml
let () =
let argl = Array.to_list Sys.argv in
print_endline (String.concat " " (List.tl argl))
|
Keep all operations the same but rewrite the snippet in OCaml. |
import sys
print " ".join(sys.argv[1:])
| #! /usr/bin/env ocaml
let () =
let argl = Array.to_list Sys.argv in
print_endline (String.concat " " (List.tl argl))
|
Write the same algorithm in OCaml as shown in this Python implementation. | def is_Curzon(n, k):
r = k * n
return pow(k, n, r + 1) == r
for k in [2, 4, 6, 8, 10]:
n, curzons = 1, []
while len(curzons) < 1000:
if is_Curzon(n, k):
curzons.append(n)
n += 1
print(f'Curzon numbers with k = {k}:')
for i, c in enumerate(curzons[:50]):
print... | let modpow m =
let rec loop p b e =
if e land 1 = 0
then if e = 0 then p else loop p (b * b mod m) (e lsr 1)
else loop (p * b mod m) (b * b mod m) (e lsr 1)
in loop 1
let is_curzon k n =
let r = k * n in r = modpow (succ r) k n
let () =
List.iter (fun x ->
Seq.(ints 0 |> filter (is_curzon x) |... |
Ensure the translated OCaml code behaves exactly like the original Python snippet. | def is_Curzon(n, k):
r = k * n
return pow(k, n, r + 1) == r
for k in [2, 4, 6, 8, 10]:
n, curzons = 1, []
while len(curzons) < 1000:
if is_Curzon(n, k):
curzons.append(n)
n += 1
print(f'Curzon numbers with k = {k}:')
for i, c in enumerate(curzons[:50]):
print... | let modpow m =
let rec loop p b e =
if e land 1 = 0
then if e = 0 then p else loop p (b * b mod m) (e lsr 1)
else loop (p * b mod m) (b * b mod m) (e lsr 1)
in loop 1
let is_curzon k n =
let r = k * n in r = modpow (succ r) k n
let () =
List.iter (fun x ->
Seq.(ints 0 |> filter (is_curzon x) |... |
Write the same algorithm in OCaml as shown in this Python implementation. | import random
class Card(object):
suits = ("Clubs","Hearts","Spades","Diamonds")
pips = ("2","3","4","5","6","7","8","9","10","Jack","Queen","King","Ace")
def __init__(self, pip,suit):
self.pip=pip
self.suit=suit
def __str__(self):
return "%s %s"%(self.pip,self.suit)
class De... | type pip = Two | Three | Four | Five | Six | Seven | Eight | Nine | Ten |
Jack | Queen | King | Ace
let pips = [Two; Three; Four; Five; Six; Seven; Eight; Nine; Ten;
Jack; Queen; King; Ace]
type suit = Diamonds | Spades | Hearts | Clubs
let suits = [Diamonds; Spades; Hearts; Clubs]
type card = ... |
Port the provided Python code into OCaml while preserving the original functionality. |
from math import gcd
def coprime(a, b):
return 1 == gcd(a, b)
def main():
print([
xy for xy in [
(21, 15), (17, 23), (36, 12),
(18, 29), (60, 15)
]
if coprime(*xy)
])
if __name__ == '__main__':
main()
| let rec is_coprime a = function
| 0 -> a = 1
| b -> is_coprime b (a mod b)
let () =
let p (a, b) =
Printf.printf "%u and %u are%s coprime\n" a b (if is_coprime a b then "" else " not")
in
List.iter p [21, 15; 17, 23; 36, 12; 18, 29; 60, 15]
|
Change the following Python code into OCaml without altering its purpose. |
from math import gcd
def coprime(a, b):
return 1 == gcd(a, b)
def main():
print([
xy for xy in [
(21, 15), (17, 23), (36, 12),
(18, 29), (60, 15)
]
if coprime(*xy)
])
if __name__ == '__main__':
main()
| let rec is_coprime a = function
| 0 -> a = 1
| b -> is_coprime b (a mod b)
let () =
let p (a, b) =
Printf.printf "%u and %u are%s coprime\n" a b (if is_coprime a b then "" else " not")
in
List.iter p [21, 15; 17, 23; 36, 12; 18, 29; 60, 15]
|
Rewrite this program in OCaml while keeping its functionality equivalent to the Python version. | def two_sum(arr, num):
i = 0
j = len(arr) - 1
while i < j:
if arr[i] + arr[j] == num:
return (i, j)
if arr[i] + arr[j] < num:
i += 1
else:
j -= 1
return None
numbers = [0, 2, 11, 19, 90]
print(two_sum(numbers, 21))
print(two_sum(numbers, 25))... | let get_sums ~numbers ~sum =
let n = Array.length numbers in
let res = ref [] in
for i = 0 to n - 2 do
for j = i + 1 to n - 1 do
if numbers.(i) + numbers.(j) = sum then
res := (i, j) :: !res
done
done;
!res
let () =
let numbers = [| 0; 2; 11; 19; 90 |]
and sum = 21
in
let res =... |
Translate the given Python code snippet into OCaml without altering its behavior. | def two_sum(arr, num):
i = 0
j = len(arr) - 1
while i < j:
if arr[i] + arr[j] == num:
return (i, j)
if arr[i] + arr[j] < num:
i += 1
else:
j -= 1
return None
numbers = [0, 2, 11, 19, 90]
print(two_sum(numbers, 21))
print(two_sum(numbers, 25))... | let get_sums ~numbers ~sum =
let n = Array.length numbers in
let res = ref [] in
for i = 0 to n - 2 do
for j = i + 1 to n - 1 do
if numbers.(i) + numbers.(j) = sum then
res := (i, j) :: !res
done
done;
!res
let () =
let numbers = [| 0; 2; 11; 19; 90 |]
and sum = 21
in
let res =... |
Maintain the same structure and functionality when rewriting this code in OCaml. | from collections import deque
def prime_digits_sum(r):
q = deque([(r, 0)])
while q:
r, n = q.popleft()
for d in 2, 3, 5, 7:
if d >= r:
if d == r: yield n + d
break
q.append((r - d, (n + d) * 10))
print(*prime_digits_sum(13))
| let prime_digits_13 =
let digits = [2; 3; 5; 7] in
let rec next ds ns = function
| [] -> if ns = [] then [] else next digits [] (List.rev ns)
| (n, r) :: cs' as cs ->
match ds with
| d :: ds' when d < r -> next ds' (((n + d) * 10, r - d) :: ns) cs
| d :: ds' when d = r -> n + d :: ne... |
Convert the following code from Python to OCaml, ensuring the logic remains intact. | from collections import deque
def prime_digits_sum(r):
q = deque([(r, 0)])
while q:
r, n = q.popleft()
for d in 2, 3, 5, 7:
if d >= r:
if d == r: yield n + d
break
q.append((r - d, (n + d) * 10))
print(*prime_digits_sum(13))
| let prime_digits_13 =
let digits = [2; 3; 5; 7] in
let rec next ds ns = function
| [] -> if ns = [] then [] else next digits [] (List.rev ns)
| (n, r) :: cs' as cs ->
match ds with
| d :: ds' when d < r -> next ds' (((n + d) * 10, r - d) :: ns) cs
| d :: ds' when d = r -> n + d :: ne... |
Preserve the algorithm and functionality while converting the code from Python to OCaml. | import copy
deepcopy_of_obj = copy.deepcopy(obj)
| let rec copy t =
if Obj.is_int t then t else
let tag = Obj.tag t in
if tag = Obj.double_tag then t else
if tag = Obj.closure_tag then t else
if tag = Obj.string_tag then Obj.repr (String.copy (Obj.obj t)) else
if tag = 0 || tag = Obj.double_array_tag then begin
let size = Obj.size t in
... |
Change the programming language of this snippet from Python to OCaml without modifying what it does. | import copy
deepcopy_of_obj = copy.deepcopy(obj)
| let rec copy t =
if Obj.is_int t then t else
let tag = Obj.tag t in
if tag = Obj.double_tag then t else
if tag = Obj.closure_tag then t else
if tag = Obj.string_tag then Obj.repr (String.copy (Obj.obj t)) else
if tag = 0 || tag = Obj.double_array_tag then begin
let size = Obj.size t in
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.