Instruction stringlengths 45 106 | input_code stringlengths 1 13.7k | output_code stringlengths 1 13.7k |
|---|---|---|
Write the same algorithm in Haskell as shown in this C implementation. | #include <stdbool.h>
#include <stdint.h>
#include <stdio.h>
uint64_t modpow(uint64_t a, uint64_t b, uint64_t n) {
uint64_t x = 1, y = a;
while (b > 0) {
if (b % 2 == 1) {
x = (x * y) % n;
}
y = (y * y) % n;
b /= 2;
}
return x % n;
}
struct Solution {
u... | import Data.List (genericTake, genericLength)
import Data.Bits (shiftR)
powMod :: Integer -> Integer -> Integer -> Integer
powMod m b e = go b e 1
where
go b e r
| e == 0 = r
| odd e = go ((b*b) `mod` m) (e `div` 2) ((r*b) `mod` m)
| even e = go ((b*b) `mod` m) (e `div` 2) r
legendre :: Inte... |
Change the following C code into Haskell without altering its purpose. |
#include <stdio.h>
#include <stdlib.h>
struct List {
struct MNode *head;
struct MNode *tail;
struct MNode *tail_pred;
};
struct MNode {
struct MNode *succ;
struct MNode *pred;
};
typedef struct MNode *NODE;
typedef struct List *LIST;
LIST newList(void);
int isEmpty(LIST);
NODE getTail(LIST);
... | import qualified Data.Map as M
type NodeID = Maybe Rational
data Node a = Node
{vNode :: a,
pNode, nNode :: NodeID}
type DLList a = M.Map Rational (Node a)
empty = M.empty
singleton a = M.singleton 0 $ Node a Nothing Nothing
fcons :: a -> DLList a -> DLList a
fcons a list | M.null list = singleton a
... |
Write the same algorithm in Haskell as shown in this C implementation. | #include <stdio.h>
#include <string.h>
#include <stdlib.h>
#define TRUE 1
#define FALSE 0
#define STACK_SIZE 80
#define BUFFER_SIZE 100
typedef int bool;
typedef struct {
char name;
bool val;
} var;
typedef struct {
int top;
bool els[STACK_SIZE];
} stack_of_bool;
char expr[BUFFER_SIZE];
int expr_le... | import Control.Monad (mapM, foldM, forever)
import Data.List (unwords, unlines, nub)
import Data.Maybe (fromJust)
truthTable expr = let
tokens = words expr
operators = ["&", "|", "!", "^", "=>"]
variables = nub $ filter (not . (`elem` operators)) tokens
table = zip variables <$> mapM (const [True,False... |
Translate this program into Haskell but keep the logic exactly as in C. | #include <stdio.h>
#include <string.h>
#include <stdlib.h>
#define TRUE 1
#define FALSE 0
#define STACK_SIZE 80
#define BUFFER_SIZE 100
typedef int bool;
typedef struct {
char name;
bool val;
} var;
typedef struct {
int top;
bool els[STACK_SIZE];
} stack_of_bool;
char expr[BUFFER_SIZE];
int expr_le... | import Control.Monad (mapM, foldM, forever)
import Data.List (unwords, unlines, nub)
import Data.Maybe (fromJust)
truthTable expr = let
tokens = words expr
operators = ["&", "|", "!", "^", "=>"]
variables = nub $ filter (not . (`elem` operators)) tokens
table = zip variables <$> mapM (const [True,False... |
Generate a Haskell translation of this C snippet without changing its computational steps. | #include <math.h>
#include <stdbool.h>
#include <stdio.h>
#include <stdlib.h>
struct RealSet {
bool(*contains)(struct RealSet*, struct RealSet*, double);
struct RealSet *left;
struct RealSet *right;
double low, high;
};
typedef enum {
CLOSED,
LEFT_OPEN,
RIGHT_OPEN,
BOTH_OPEN,
} RangeTy... |
import Data.List
import Data.Maybe
data BracketType = OpenSub | ClosedSub
deriving (Show, Enum, Eq, Ord)
data RealInterval = RealInterval {left :: BracketType, right :: BracketType,
lowerBound :: Double, upperBound :: Double}
deriving (Eq)
type RealSet = [RealInterval]
posInf = 1.0/0.0 :: Double
negI... |
Port the following code from C to Haskell with equivalent syntax and logic. | #include <math.h>
#include <stdbool.h>
#include <stdio.h>
#include <stdlib.h>
struct RealSet {
bool(*contains)(struct RealSet*, struct RealSet*, double);
struct RealSet *left;
struct RealSet *right;
double low, high;
};
typedef enum {
CLOSED,
LEFT_OPEN,
RIGHT_OPEN,
BOTH_OPEN,
} RangeTy... |
import Data.List
import Data.Maybe
data BracketType = OpenSub | ClosedSub
deriving (Show, Enum, Eq, Ord)
data RealInterval = RealInterval {left :: BracketType, right :: BracketType,
lowerBound :: Double, upperBound :: Double}
deriving (Eq)
type RealSet = [RealInterval]
posInf = 1.0/0.0 :: Double
negI... |
Generate a Haskell translation of this C snippet without changing its computational steps. | #include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define USE_FAKES 1
const char *states[] = {
#if USE_FAKES
"New Kory", "Wen Kory", "York New", "Kory New", "New Kory",
#endif
"Alabama", "Alaska", "Arizona", "Arkansas",
"California", "Colorado", "Connecticut",
"Delaware",
"Florida", "Georgia", "Hawa... |
import Data.Char (isLetter, toLower)
import Data.Function (on)
import Data.List (groupBy, nub, sort, sortBy)
puzzle :: [String] -> [((String, String), (String, String))]
puzzle states =
concatMap
((filter isValid . pairs) . map snd)
( filter ((> 1) . length) $
groupBy ((==) `on` fst) $
... |
Transform the following C implementation into Haskell, maintaining the same output and logic. | #include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <gmp.h>
int main() {
for (unsigned int d = 2; d <= 9; ++d) {
printf("First 10 super-%u numbers:\n", d);
char digits[16] = { 0 };
memset(digits, '0' + d, d);
mpz_t bignum;
mpz_init(bignum);
for (unsig... | import Data.List (isInfixOf)
import Data.Char (intToDigit)
isSuperd :: (Show a, Integral a) => a -> a -> Bool
isSuperd p n =
(replicate <*> intToDigit) (fromIntegral p) `isInfixOf` show (p * n ^ p)
findSuperd :: (Show a, Integral a) => a -> [a]
findSuperd p = filter (isSuperd p) [1 ..]
main :: IO ()
main =
mapM_... |
Maintain the same structure and functionality when rewriting this code in Haskell. | #include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <gmp.h>
int main() {
for (unsigned int d = 2; d <= 9; ++d) {
printf("First 10 super-%u numbers:\n", d);
char digits[16] = { 0 };
memset(digits, '0' + d, d);
mpz_t bignum;
mpz_init(bignum);
for (unsig... | import Data.List (isInfixOf)
import Data.Char (intToDigit)
isSuperd :: (Show a, Integral a) => a -> a -> Bool
isSuperd p n =
(replicate <*> intToDigit) (fromIntegral p) `isInfixOf` show (p * n ^ p)
findSuperd :: (Show a, Integral a) => a -> [a]
findSuperd p = filter (isSuperd p) [1 ..]
main :: IO ()
main =
mapM_... |
Convert the following code from C to Haskell, ensuring the logic remains intact. | #include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <string.h>
int pRec(int n) {
static int *memo = NULL;
static size_t curSize = 0;
if (curSize <= (size_t) n) {
size_t lastSize = curSize;
while (curSize <= (size_t) n) curSize += 1024 * sizeof(int);
memo = r... |
pRec = map (\(a,_,_) -> a) $ iterate (\(a,b,c) -> (b,c,a+b)) (1,1,1)
pSelfRef = 1 : 1 : 1 : zipWith (+) pSelfRef (tail pSelfRef)
pFloor = map f [0..]
where f n = floor $ p**fromInteger (pred n) / s + 0.5
p = 1.324717957244746025960908854
s = 1.0453567932525329623
lSystem = ... |
Change the following C code into Haskell without altering its purpose. | #include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
typedef enum type
{
INT,
STRING
} Type;
typedef struct maybe
{
int i;
char *s;
Type t;
_Bool is_something;
} Maybe;
void print_Maybe(Maybe *m)
{
if (m->t == INT)
printf("Just %d : INT\n", m->i);
else if (m->t == STRING)
printf("Just... | main = do print $ Just 3 >>= (return . (*2)) >>= (return . (+1))
print $ Nothing >>= (return . (*2)) >>= (return . (+1))
|
Convert this C snippet to Haskell and keep its semantics consistent. | #include <stdio.h>
#include <stdlib.h>
#define MONAD void*
#define INTBIND(f, g, x) (f((int*)g(x)))
#define RETURN(type,x) &((type)*)(x)
MONAD boundInt(int *x) {
return (MONAD)(x);
}
MONAD boundInt2str(int *x) {
char buf[100];
char*str= malloc(1+sprintf(buf, "%d", *x));
sprintf(str, "%d", *x);
re... | main = print $ [3,4,5] >>= (return . (+1)) >>= (return . (*2))
|
Write a version of this C function in Haskell with identical behavior. | #include <stdbool.h>
#include <stdio.h>
#include <stdlib.h>
#include <glib.h>
char text_char(char c) {
switch (c) {
case 'a': case 'b': case 'c':
return '2';
case 'd': case 'e': case 'f':
return '3';
case 'g': case 'h': case 'i':
return '4';
case 'j': case 'k': case 'l':
... | import Data.Char (toUpper)
import Data.Function (on)
import Data.List (groupBy, sortBy)
import Data.Maybe (fromMaybe, isJust, isNothing)
toKey :: Char -> Maybe Char
toKey ch
| ch < 'A' = Nothing
| ch < 'D' = Just '2'
| ch < 'G' = Just '3'
| ch < 'J' = Just '4'
| ch < 'M' = Just '5'
| ch < 'P' = Just '6'
... |
Port the provided C code into Haskell while preserving the original functionality. | #include <stdio.h>
#include <string.h>
#include <ctype.h>
#include <openssl/sha.h>
#include <openssl/ripemd.h>
#define COIN_VER 0
const char *coin_err;
typedef unsigned char byte;
int is_hex(const char *s) {
int i;
for (i = 0; i < 64; i++)
if (!isxdigit(s[i])) return 0;
return 1;
}
void str_to_byte(const char ... | import Numeric (showIntAtBase)
import Data.List (unfoldr)
import Data.Binary (Word8)
import Crypto.Hash.SHA256 as S (hash)
import Crypto.Hash.RIPEMD160 as R (hash)
import Data.ByteString (unpack, pack)
publicPointToAddress :: Integer -> Integer -> String
publicPointToAddress x y =
let toBytes x = reverse $ unfoldr ... |
Convert the following code from C to Haskell, ensuring the logic remains intact. | #include <stdio.h>
#include <string.h>
#include <ctype.h>
#include <openssl/sha.h>
#include <openssl/ripemd.h>
#define COIN_VER 0
const char *coin_err;
typedef unsigned char byte;
int is_hex(const char *s) {
int i;
for (i = 0; i < 64; i++)
if (!isxdigit(s[i])) return 0;
return 1;
}
void str_to_byte(const char ... | import Numeric (showIntAtBase)
import Data.List (unfoldr)
import Data.Binary (Word8)
import Crypto.Hash.SHA256 as S (hash)
import Crypto.Hash.RIPEMD160 as R (hash)
import Data.ByteString (unpack, pack)
publicPointToAddress :: Integer -> Integer -> String
publicPointToAddress x y =
let toBytes x = reverse $ unfoldr ... |
Translate this program into Haskell but keep the logic exactly as in C. | #include <stdbool.h>
#include <stdio.h>
#include <stdint.h>
typedef struct cidr_tag {
uint32_t address;
unsigned int mask_length;
} cidr_t;
bool cidr_parse(const char* str, cidr_t* cidr) {
int a, b, c, d, m;
if (sscanf(str, "%d.%d.%d.%d/%d", &a, &b, &c, &d, &m) != 5)
return false;
if (m ... | import Control.Monad (guard)
import Data.Bits ((.|.), (.&.), complement, shiftL, shiftR, zeroBits)
import Data.Maybe (listToMaybe)
import Data.Word (Word32, Word8)
import Text.ParserCombinators.ReadP (ReadP, char, readP_to_S)
import Text.Printf (printf)
import Text.Read.Lex (readDecP)
data CIDR = CIDR Word32 Word8
... |
Maintain the same structure and functionality when rewriting this code in Haskell. | #include <stdbool.h>
#include <stdio.h>
#include <stdint.h>
typedef struct cidr_tag {
uint32_t address;
unsigned int mask_length;
} cidr_t;
bool cidr_parse(const char* str, cidr_t* cidr) {
int a, b, c, d, m;
if (sscanf(str, "%d.%d.%d.%d/%d", &a, &b, &c, &d, &m) != 5)
return false;
if (m ... | import Control.Monad (guard)
import Data.Bits ((.|.), (.&.), complement, shiftL, shiftR, zeroBits)
import Data.Maybe (listToMaybe)
import Data.Word (Word32, Word8)
import Text.ParserCombinators.ReadP (ReadP, char, readP_to_S)
import Text.Printf (printf)
import Text.Read.Lex (readDecP)
data CIDR = CIDR Word32 Word8
... |
Ensure the translated Haskell code behaves exactly like the original C snippet. | #include <gmp.h>
int main(void)
{
mpz_t p, s;
mpz_init_set_ui(p, 1);
mpz_init_set_ui(s, 1);
for (int n = 1, i = 0; i < 20; n++) {
mpz_nextprime(s, s);
mpz_mul(p, p, s);
mpz_add_ui(p, p, 1);
if (mpz_probab_prime_p(p, 25)) {
mpz_sub_ui(p, p, 1);
g... | import Data.List (scanl1, elemIndices, nub)
primes :: [Integer]
primes = 2 : filter isPrime [3,5 ..]
isPrime :: Integer -> Bool
isPrime = isPrime_ primes
where
isPrime_ :: [Integer] -> Integer -> Bool
isPrime_ (p:ps) n
| p * p > n = True
| n `mod` p == 0 = False
| otherwise = isPrime_ ps n... |
Convert this C block to Haskell, preserving its control flow and logic. | #include <gmp.h>
void perm(mpz_t out, int n, int k)
{
mpz_set_ui(out, 1);
k = n - k;
while (n > k) mpz_mul_ui(out, out, n--);
}
void comb(mpz_t out, int n, int k)
{
perm(out, n, k);
while (k) mpz_divexact_ui(out, out, k--);
}
int main(void)
{
mpz_t x;
mpz_init(x);
perm(x, 1000, 969);
gmp_printf("P(1000,969... | perm :: Integer -> Integer -> Integer
perm n k = product [n-k+1..n]
comb :: Integer -> Integer -> Integer
comb n k = perm n k `div` product [1..k]
main :: IO ()
main = do
let showBig maxlen b =
let st = show b
stlen = length st
in if stlen < maxlen then st e... |
Translate the given C code snippet into Haskell without altering its behavior. | #include "gmp.h"
void agm (const mpf_t in1, const mpf_t in2, mpf_t out1, mpf_t out2) {
mpf_add (out1, in1, in2);
mpf_div_ui (out1, out1, 2);
mpf_mul (out2, in1, in2);
mpf_sqrt (out2, out2);
}
int main (void) {
mpf_set_default_prec (300000);
mpf_t x0, y0, resA, resB, Z, var;
mpf_init_set_ui (x0, 1);
mpf_init_... | import Prelude hiding (pi)
import Data.Number.MPFR hiding (sqrt, pi, div)
import Data.Number.MPFR.Instances.Near ()
digitBits :: (Integral a, Num a) => a -> a
digitBits n = (n + 1) `div` 2 * 8
pi :: Integer -> MPFR
pi digits =
let eps = fromString ("1e-" ++ show digits)
(fromInteger $ digitBits digit... |
Convert this C block to Haskell, preserving its control flow and logic. | #include "gmp.h"
void agm (const mpf_t in1, const mpf_t in2, mpf_t out1, mpf_t out2) {
mpf_add (out1, in1, in2);
mpf_div_ui (out1, out1, 2);
mpf_mul (out2, in1, in2);
mpf_sqrt (out2, out2);
}
int main (void) {
mpf_set_default_prec (300000);
mpf_t x0, y0, resA, resB, Z, var;
mpf_init_set_ui (x0, 1);
mpf_init_... | import Prelude hiding (pi)
import Data.Number.MPFR hiding (sqrt, pi, div)
import Data.Number.MPFR.Instances.Near ()
digitBits :: (Integral a, Num a) => a -> a
digitBits n = (n + 1) `div` 2 * 8
pi :: Integer -> MPFR
pi digits =
let eps = fromString ("1e-" ++ show digits)
(fromInteger $ digitBits digit... |
Translate this program into Haskell but keep the logic exactly as in C. | '--- added a flush to exit cleanly
PRAGMA LDFLAGS `pkg-config --cflags --libs x11`
PRAGMA INCLUDE <X11/Xlib.h>
PRAGMA INCLUDE <X11/Xutil.h>
OPTION PARSE FALSE
'---XLIB is so ugly
ALIAS XNextEvent TO EVENT
ALIAS XOpenDisplay TO DISPLAY
ALIAS DefaultScreen TO SCREEN
ALIAS XCreateSimpleWindow TO CREATE
ALIAS XCloseD... | import Graphics.X11.Xlib
import Control.Concurrent (threadDelay)
main = do
display <- openDisplay ""
let defScr = defaultScreen display
rw <- rootWindow display defScr
xwin <- createSimpleWindow display rw
0 0 400 200 1
(blackPixel display defScr)
(whitePixel display defScr)
setTextProper... |
Generate an equivalent Haskell version of this C code. | #include <stdio.h>
#include <stdlib.h>
#define TRUE 1
#define FALSE 0
typedef int bool;
void sieve(int limit, int primes[], int *count) {
bool *c = calloc(limit + 1, sizeof(bool));
int i, p = 3, p2, n = 0;
p2 = p * p;
while (p2 <= limit) {
for (i = p2; i <= limit; i += 2 * p)
... | import Data.List (elemIndex)
longPrimesUpTo :: Int -> [Int]
longPrimesUpTo n =
filter isLongPrime $
takeWhile (< n) primes
where
sieve (p : xs) = p : sieve [x | x <- xs, x `mod` p /= 0]
primes = sieve [2 ..]
isLongPrime n = found
where
cycles = take n (iterate ((`mod` n) . (10 *)) 1)
... |
Change the programming language of this snippet from C to Haskell without modifying what it does. | #include <inttypes.h>
#include <math.h>
#include <stdlib.h>
#include <stdio.h>
#include <stdint.h>
#include <string.h>
#include <gmp.h>
int es_check(uint32_t *sieve, uint64_t n)
{
if ((n != 2 && !(n & 1)) || (n < 2))
return 0;
else
return !(sieve[n >> 6] & (1 << (n >> 1 & 31)));
}
uint32_t *e... | import Control.Arrow ((&&&))
import Data.List (scanl1, foldl1')
getNthPrimorial :: Int -> Integer
getNthPrimorial n = foldl1' (*) (take n primes)
primes :: [Integer]
primes = 2 : filter isPrime [3,5..]
isPrime :: Integer -> Bool
isPrime = isPrime_ primes
where isPrime_ :: [Integer] -> Integer -> Bool
isPri... |
Maintain the same structure and functionality when rewriting this code in Haskell. | #include <stdbool.h>
#include <stdint.h>
#include <stdio.h>
typedef int64_t integer;
struct Pair {
integer md;
int tc;
};
integer mod(integer x, integer y) {
return ((x % y) + y) % y;
}
integer gcd(integer a, integer b) {
if (0 == a) return b;
if (0 == b) return a;
if (a == b) return a;
... | import Data.Ratio (Ratio, (%), denominator, numerator)
egyptianFraction :: Integral a => Ratio a -> [Ratio a]
egyptianFraction n
| n < 0 = map negate (egyptianFraction (-n))
| n == 0 = []
| x == 1 = [n]
| x > y = (x `div` y % 1) : egyptianFraction (x `mod` y % y)
| otherwise = (1 % r) : egyptianFraction ((-y... |
Maintain the same structure and functionality when rewriting this code in Haskell. | #include <stdbool.h>
#include <stdint.h>
#include <stdio.h>
typedef int64_t integer;
struct Pair {
integer md;
int tc;
};
integer mod(integer x, integer y) {
return ((x % y) + y) % y;
}
integer gcd(integer a, integer b) {
if (0 == a) return b;
if (0 == b) return a;
if (a == b) return a;
... | import Data.Ratio (Ratio, (%), denominator, numerator)
egyptianFraction :: Integral a => Ratio a -> [Ratio a]
egyptianFraction n
| n < 0 = map negate (egyptianFraction (-n))
| n == 0 = []
| x == 1 = [n]
| x > y = (x `div` y % 1) : egyptianFraction (x `mod` y % y)
| otherwise = (1 % r) : egyptianFraction ((-y... |
Produce a functionally identical Haskell code for the snippet given in C. | #include <stdio.h>
#include <math.h>
#define N 5
double Pi;
double lroots[N];
double weight[N];
double lcoef[N + 1][N + 1] = {{0}};
void lege_coef()
{
int n, i;
lcoef[0][0] = lcoef[1][1] = 1;
for (n = 2; n <= N; n++) {
lcoef[n][0] = -(n - 1) * lcoef[n - 2][0] / n;
for (i = 1; i <= n; i++)
lcoef[n][i] = ((2 ... | gaussLegendre n f a b = d*sum [ w x*f(m + d*x) | x <- roots ]
where d = (b - a)/2
m = (b + a)/2
w x = 2/(1-x^2)/(legendreP' n x)^2
roots = map (findRoot (legendreP n) (legendreP' n) . x0) [1..n]
x0 i = cos (pi*(i-1/4)/(n+1/2))
|
Can you help me rewrite this code in Haskell instead of C, keeping it the same logically? | #include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <math.h>
#include <time.h>
#define MAX_DIM 3
struct kd_node_t{
double x[MAX_DIM];
struct kd_node_t *left, *right;
};
inline double
dist(struct kd_node_t *a, struct kd_node_t *b, int dim)
{
double t, d = 0;
while (dim--) {
... | import System.Random
import Data.List (sortBy, genericLength, minimumBy)
import Data.Ord (comparing)
type DimensionalAccessors a b = [a -> b]
data Tree a = Node a (Tree a) (Tree a)
| Empty
instance Show a => Show (Tree a) where
show Empty = "Empty"
show (Node value left right) =
"(" ++ show va... |
Change the following C code into Haskell without altering its purpose. | #include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <math.h>
#include <time.h>
#define MAX_DIM 3
struct kd_node_t{
double x[MAX_DIM];
struct kd_node_t *left, *right;
};
inline double
dist(struct kd_node_t *a, struct kd_node_t *b, int dim)
{
double t, d = 0;
while (dim--) {
... | import System.Random
import Data.List (sortBy, genericLength, minimumBy)
import Data.Ord (comparing)
type DimensionalAccessors a b = [a -> b]
data Tree a = Node a (Tree a) (Tree a)
| Empty
instance Show a => Show (Tree a) where
show Empty = "Empty"
show (Node value left right) =
"(" ++ show va... |
Preserve the algorithm and functionality while converting the code from C to Haskell. | typedef struct oct_node_t oct_node_t, *oct_node;
struct oct_node_t{
uint64_t r, g, b;
int count, heap_idx;
oct_node kids[8], parent;
unsigned char n_kids, kid_idx, flags, depth;
};
inline int cmp_node(oct_node a, oct_node b)
{
if (a->n_kids < b->n_kids) return -1;
if (a->n_kids > b->n_kids) return 1;
int ac... | import qualified Data.ByteString.Lazy as BS
import qualified Data.Foldable as Fold
import qualified Data.List as List
import Data.Ord
import qualified Data.Sequence as Seq
import Data.Word
import System.Environment
import Codec.Picture
import Codec.Picture.Types
type Accessor = PixelRGB8 -> Pixel8
red, blue, green... |
Please provide an equivalent version of this C code in Haskell. | #include <stdio.h>
#include <stdlib.h>
#include <string.h>
typedef unsigned char byte;
byte *grid = 0;
int w, h, len;
unsigned long long cnt;
static int next[4], dir[4][2] = {{0, -1}, {-1, 0}, {0, 1}, {1, 0}};
void walk(int y, int x)
{
int i, t;
if (!y || y == h || !x || x == w) {
cnt += 2;
return;
}
t = y... | import qualified Data.Vector.Unboxed.Mutable as V
import Data.STRef
import Control.Monad (forM_, when)
import Control.Monad.ST
dir :: [(Int, Int)]
dir = [(1, 0), (-1, 0), (0, -1), (0, 1)]
data Env = Env { w, h, len, count, ret :: !Int, next :: ![Int] }
cutIt :: STRef s Env -> ST s ()
cutIt env = do
e <- readSTRe... |
Convert the following code from C to Haskell, ensuring the logic remains intact. | #include <stdio.h>
#include <stdlib.h>
#include <string.h>
typedef unsigned char byte;
byte *grid = 0;
int w, h, len;
unsigned long long cnt;
static int next[4], dir[4][2] = {{0, -1}, {-1, 0}, {0, 1}, {1, 0}};
void walk(int y, int x)
{
int i, t;
if (!y || y == h || !x || x == w) {
cnt += 2;
return;
}
t = y... | import qualified Data.Vector.Unboxed.Mutable as V
import Data.STRef
import Control.Monad (forM_, when)
import Control.Monad.ST
dir :: [(Int, Int)]
dir = [(1, 0), (-1, 0), (0, -1), (0, 1)]
data Env = Env { w, h, len, count, ret :: !Int, next :: ![Int] }
cutIt :: STRef s Env -> ST s ()
cutIt env = do
e <- readSTRe... |
Keep all operations the same but rewrite the snippet in Haskell. | #include <limits.h>
#include <math.h>
#include <stdbool.h>
#include <stdio.h>
#include <stdlib.h>
typedef long long llong_t;
struct PrimeArray {
llong_t *ptr;
size_t size;
size_t capacity;
};
struct PrimeArray allocate() {
struct PrimeArray primes;
primes.size = 0;
primes.capacity = 10;
p... | import Data.Numbers.Primes (isPrime)
import Data.List (intercalate)
import Data.List.Split (chunksOf)
import Text.Printf (printf)
cubans :: [Int]
cubans = filter isPrime . map (\x -> (succ x ^ 3) - (x ^ 3)) $ [1 ..]
main :: IO ()
main = do
mapM_ (\row -> mapM_ (printf "%10s" . thousands) row >> printf "\n") $ rows ... |
Please provide an equivalent version of this C code in Haskell. | #include<graphics.h>
#include<stdlib.h>
#include<stdio.h>
#include<math.h>
#include<time.h>
#define pi M_PI
int main(){
time_t t;
double side, vertices[3][3],seedX,seedY,windowSide;
int i,iter,choice;
printf("Enter triangle side length : ");
scanf("%lf",&side);
printf("Enter number of iterations : ");
sc... | import Control.Monad (replicateM)
import Control.Monad.Random (fromList)
type Point = (Float,Float)
type Transformations = [(Point -> Point, Float)]
gameOfChaos :: MonadRandom m => Int -> Transformations -> Point -> m [Point]
gameOfChaos n transformations x = iterateA (fromList transformations) x
where iterateA f... |
Rewrite this program in Haskell while keeping its functionality equivalent to the C version. | #include<graphics.h>
#include<stdlib.h>
#include<stdio.h>
#include<math.h>
#include<time.h>
#define pi M_PI
int main(){
time_t t;
double side, vertices[3][3],seedX,seedY,windowSide;
int i,iter,choice;
printf("Enter triangle side length : ");
scanf("%lf",&side);
printf("Enter number of iterations : ");
sc... | import Control.Monad (replicateM)
import Control.Monad.Random (fromList)
type Point = (Float,Float)
type Transformations = [(Point -> Point, Float)]
gameOfChaos :: MonadRandom m => Int -> Transformations -> Point -> m [Point]
gameOfChaos n transformations x = iterateA (fromList transformations) x
where iterateA f... |
Translate this program into Haskell but keep the logic exactly as in C. | #include <sys/types.h>
#include <regex.h>
#include <stdio.h>
typedef struct {
const char *s;
int len, prec, assoc;
} str_tok_t;
typedef struct {
const char * str;
int assoc, prec;
regex_t re;
} pat_t;
enum assoc { A_NONE, A_L, A_R };
pat_t pat_eos = {"", A_NONE, 0};
pat_t pat_ops[] = {
{"^\\)", A_NONE, -1},
... | import Text.Printf
prec :: String -> Int
prec "^" = 4
prec "*" = 3
prec "/" = 3
prec "+" = 2
prec "-" = 2
leftAssoc :: String -> Bool
leftAssoc "^" = False
leftAssoc _ = True
isOp :: String -> Bool
isOp [t] = t `elem` "-+/*^"
isOp _ = False
simSYA :: [String] -> [([String], [String], String)]
simSYA xs = final <> [... |
Generate a Haskell translation of this C snippet without changing its computational steps. | #include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <float.h>
#include <iso646.h>
#include <math.h>
#define map_size_rows 10
#define map_size_cols 10
char map[map_size_rows][map_size_cols] = {
{1, 1, 1, 1, 1, 1, 1, 1, 1, 1},
{1, 0, 0, 0, 0, 0, 0, 0, 0, 1},
{1, 0, 0, 0, 0, 0, 0, 0, 0, 1},... |
module PQueue where
data PQueue a = EmptyQueue
| Node (Int, a) (PQueue a) (PQueue a)
deriving (Show, Foldable)
instance Ord a => Semigroup (PQueue a) where
h1@(Node (w1, x1) l1 r1) <> h2@(Node (w2, x2) l2 r2)
| w1 < w2 = Node (w1, x1) (h2 <> r1) l1
| otherwise = Node (w2, x2) (h1 <> r2) ... |
Write the same algorithm in Haskell as shown in this C implementation. | #include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <float.h>
#include <iso646.h>
#include <math.h>
#define map_size_rows 10
#define map_size_cols 10
char map[map_size_rows][map_size_cols] = {
{1, 1, 1, 1, 1, 1, 1, 1, 1, 1},
{1, 0, 0, 0, 0, 0, 0, 0, 0, 1},
{1, 0, 0, 0, 0, 0, 0, 0, 0, 1},... |
module PQueue where
data PQueue a = EmptyQueue
| Node (Int, a) (PQueue a) (PQueue a)
deriving (Show, Foldable)
instance Ord a => Semigroup (PQueue a) where
h1@(Node (w1, x1) l1 r1) <> h2@(Node (w2, x2) l2 r2)
| w1 < w2 = Node (w1, x1) (h2 <> r1) l1
| otherwise = Node (w2, x2) (h1 <> r2) ... |
Transform the following C implementation into Haskell, maintaining the same output and logic. |
#include <stdio.h>
#include <stddef.h>
#include <string.h>
#ifdef _MSC_VER
typedef unsigned __int32 uint32_t;
#else
#include <stdint.h>
#endif
typedef uint32_t ub4;
ub4 randrsl[256], randcnt;
static ub4 mm[256];
static ub4 aa=0, bb=0, cc=0;
void isaac()
{
register ub4 i,x,y;
cc = cc + 1;
... | import Data.Array (Array, (!), (//), array, elems)
import Data.Word (Word, Word32)
import Data.Bits (shift, xor)
import Data.Char (toUpper)
import Data.List (unfoldr)
import Numeric (showHex)
type IArray = Array Word32 Word32
data IsaacState = IState
{ randrsl :: IArray
, randcnt :: Word32
, mm :: IArray
, aa... |
Keep all operations the same but rewrite the snippet in Haskell. |
#include <stdio.h>
#include <stddef.h>
#include <string.h>
#ifdef _MSC_VER
typedef unsigned __int32 uint32_t;
#else
#include <stdint.h>
#endif
typedef uint32_t ub4;
ub4 randrsl[256], randcnt;
static ub4 mm[256];
static ub4 aa=0, bb=0, cc=0;
void isaac()
{
register ub4 i,x,y;
cc = cc + 1;
... | import Data.Array (Array, (!), (//), array, elems)
import Data.Word (Word, Word32)
import Data.Bits (shift, xor)
import Data.Char (toUpper)
import Data.List (unfoldr)
import Numeric (showHex)
type IArray = Array Word32 Word32
data IsaacState = IState
{ randrsl :: IArray
, randcnt :: Word32
, mm :: IArray
, aa... |
Produce a functionally identical Haskell code for the snippet given in C. | #include <stdio.h>
#include <stdlib.h>
#define SWAP(a,b) do{t=(a);(a)=(b);(b)=t;}while(0)
void _mr_unrank1(int rank, int n, int *vec) {
int t, q, r;
if (n < 1) return;
q = rank / n;
r = rank % n;
SWAP(vec[r], vec[n-1]);
_mr_unrank1(q, n-1, vec);
}
int _mr_rank1(int n, int *vec, int *inv) {
... | fact :: Int -> Int
fact n = product [1 .. n]
rankPerm [] _ = []
rankPerm list n = c : rankPerm (a ++ b) r
where
(q, r) = n `divMod` fact (length list - 1)
(a, c:b) = splitAt q list
permRank [] = 0
permRank (x:xs) = length (filter (< x) xs) * fact (length xs) + permRank xs
main :: IO ()
main = mapM_ f [0 ... |
Keep all operations the same but rewrite the snippet in Haskell. | #include <stdio.h>
#include <stdlib.h>
#define SWAP(a,b) do{t=(a);(a)=(b);(b)=t;}while(0)
void _mr_unrank1(int rank, int n, int *vec) {
int t, q, r;
if (n < 1) return;
q = rank / n;
r = rank % n;
SWAP(vec[r], vec[n-1]);
_mr_unrank1(q, n-1, vec);
}
int _mr_rank1(int n, int *vec, int *inv) {
... | fact :: Int -> Int
fact n = product [1 .. n]
rankPerm [] _ = []
rankPerm list n = c : rankPerm (a ++ b) r
where
(q, r) = n `divMod` fact (length list - 1)
(a, c:b) = splitAt q list
permRank [] = 0
permRank (x:xs) = length (filter (< x) xs) * fact (length xs) + permRank xs
main :: IO ()
main = mapM_ f [0 ... |
Change the following C code into Haskell without altering its purpose. | #include <math.h>
#include <stdio.h>
int p(int l, int n) {
int test = 0;
double logv = log(2.0) / log(10.0);
int factor = 1;
int loop = l;
while (loop > 10) {
factor *= 10;
loop /= 10;
}
while (n > 0) {
int val;
test++;
val = (int)(factor * pow(10.0,... | import Control.Monad (guard)
import Text.Printf (printf)
p :: Int -> Int -> Int
p l n = calc !! pred n
where
digitCount = floor $ logBase 10 (fromIntegral l :: Float)
log10pwr = logBase 10 2
calc = do
raised <- [-1 ..]
let firstDigits = floor $ 10 ** (snd (properFracti... |
Produce a language-to-language conversion: from C to Haskell, same semantics. | #include <math.h>
#include <stdio.h>
int p(int l, int n) {
int test = 0;
double logv = log(2.0) / log(10.0);
int factor = 1;
int loop = l;
while (loop > 10) {
factor *= 10;
loop /= 10;
}
while (n > 0) {
int val;
test++;
val = (int)(factor * pow(10.0,... | import Control.Monad (guard)
import Text.Printf (printf)
p :: Int -> Int -> Int
p l n = calc !! pred n
where
digitCount = floor $ logBase 10 (fromIntegral l :: Float)
log10pwr = logBase 10 2
calc = do
raised <- [-1 ..]
let firstDigits = floor $ 10 ** (snd (properFracti... |
Rewrite this program in Haskell while keeping its functionality equivalent to the C version. | #include <stdbool.h>
#include <stdio.h>
#include <stdlib.h>
typedef struct stirling_cache_tag {
int max;
int* values;
} stirling_cache;
int stirling_number2(stirling_cache* sc, int n, int k) {
if (k == n)
return 1;
if (k == 0 || k > n || n > sc->max)
return 0;
return sc->values[n*(... | import Text.Printf (printf)
import Data.List (groupBy)
import qualified Data.MemoCombinators as Memo
stirling2 :: Integral a => (a, a) -> a
stirling2 = Memo.pair Memo.integral Memo.integral f
where
f (n, k)
| n == 0 && k == 0 = 1
| (n > 0 && k == 0) || (n == 0 && k > 0) = 0
| n == k = 1
|... |
Can you help me rewrite this code in Haskell instead of C, keeping it the same logically? | #include <stdbool.h>
#include <stdio.h>
#include <stdlib.h>
typedef struct stirling_cache_tag {
int max;
int* values;
} stirling_cache;
int stirling_number2(stirling_cache* sc, int n, int k) {
if (k == n)
return 1;
if (k == 0 || k > n || n > sc->max)
return 0;
return sc->values[n*(... | import Text.Printf (printf)
import Data.List (groupBy)
import qualified Data.MemoCombinators as Memo
stirling2 :: Integral a => (a, a) -> a
stirling2 = Memo.pair Memo.integral Memo.integral f
where
f (n, k)
| n == 0 && k == 0 = 1
| (n > 0 && k == 0) || (n == 0 && k > 0) = 0
| n == k = 1
|... |
Maintain the same structure and functionality when rewriting this code in Haskell. | #include <stdbool.h>
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
const int PRIMES[] = {
2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47,
53, 59, 61, 67, 71, 73, 79, 83, 89, 97, 101, 103, 107, 109, 113,
127, 131, 137, 139, 149, 151, 157,... | import Control.Monad (guard)
import Data.List (intercalate)
import Data.List.Split (chunksOf)
import Math.NumberTheory.Primes (Prime, unPrime, nextPrime)
import Math.NumberTheory.Primes.Testing (isPrime)
import Text.Printf (printf)
data PierPointKind = First | Second
merge :: Ord a => [a] -> [a] -> [a]
merge [] b = b... |
Change the following C code into Haskell without altering its purpose. | #include <stdbool.h>
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <gmp.h>
void* xmalloc(size_t n) {
void* ptr = malloc(n);
if (ptr == NULL) {
fprintf(stderr, "Out of memory\n");
exit(1);
}
return ptr;
}
void* xrealloc(void* p, size_t n) {
void* ptr = realloc(... | import Data.Numbers.Primes (primes)
import Text.Printf (printf)
merge :: Ord a => [a] -> [a] -> [a]
merge [] b = b
merge a@(x:xs) b@(y:ys) | x < y = x : merge xs b
| otherwise = y : merge a ys
nSmooth :: Integer -> [Integer]
nSmooth p = 1 : foldr u [] factors
where
factors = takeWhi... |
Preserve the algorithm and functionality while converting the code from C to Haskell. | #include <assert.h>
#include <stdbool.h>
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
typedef struct bit_array_tag {
uint32_t size;
uint32_t* array;
} bit_array;
bool bit_array_create(bit_array* b, uint32_t size) {
uint32_t* array = calloc((size + 31)/32, sizeof(uint32_t));
if (array == ... | import Data.List (delete, intercalate)
import Data.Numbers.Primes (primes)
import Data.Bool (bool)
partitions :: Int -> Int -> [Int]
partitions x n
| n <= 1 =
[ x
| x == last ps ]
| otherwise = go ps x n
where
ps = takeWhile (<= x) primes
go ps_ x 1 =
[ x
| x `elem` ps_ ]
go ps_ ... |
Produce a language-to-language conversion: from C to Haskell, same semantics. | #include <stdbool.h>
#include <stdio.h>
#include <string.h>
int inv(int a) {
return a ^ -1;
}
struct Zeckendorf {
int dVal, dLen;
};
void a(struct Zeckendorf *self, int n) {
void b(struct Zeckendorf *, int);
int i = n;
while (true) {
if (self->dLen < i) self->dLen = i;
int j = (... |
import Data.List (find, mapAccumL)
import Control.Arrow (first, second)
fibs :: Num a => a -> a -> [a]
fibs a b = res
where
res = a : b : zipWith (+) res (tail res)
data Fib = Fib { sign :: Int, digits :: [Int]}
mkFib s ds =
case dropWhile (==0) ds of
[] -> 0
ds -> Fib s (reverse ds)
instance S... |
Convert this C snippet to Haskell and keep its semantics consistent. | #include <stdbool.h>
#include <stdio.h>
#include <stdlib.h>
typedef struct stirling_cache_tag {
int max;
int* values;
} stirling_cache;
int stirling_number1(stirling_cache* sc, int n, int k) {
if (k == 0)
return n == 0 ? 1 : 0;
if (n > sc->max || k > n)
return 0;
return sc->values[... | import Text.Printf (printf)
import Data.List (groupBy)
import qualified Data.MemoCombinators as Memo
stirling1 :: Integral a => (a, a) -> a
stirling1 = Memo.pair Memo.integral Memo.integral f
where
f (n, k)
| n == 0 && k == 0 = 1
| n > 0 && k == 0 = 0
| k > n = 0
| otherwise =... |
Generate a Haskell translation of this C snippet without changing its computational steps. | #include <stdbool.h>
#include <stdio.h>
#include <stdlib.h>
typedef struct stirling_cache_tag {
int max;
int* values;
} stirling_cache;
int stirling_number1(stirling_cache* sc, int n, int k) {
if (k == 0)
return n == 0 ? 1 : 0;
if (n > sc->max || k > n)
return 0;
return sc->values[... | import Text.Printf (printf)
import Data.List (groupBy)
import qualified Data.MemoCombinators as Memo
stirling1 :: Integral a => (a, a) -> a
stirling1 = Memo.pair Memo.integral Memo.integral f
where
f (n, k)
| n == 0 && k == 0 = 1
| n > 0 && k == 0 = 0
| k > n = 0
| otherwise =... |
Preserve the algorithm and functionality while converting the code from C to Haskell. | #include<stdio.h>
#include<math.h>
#define pi M_PI
typedef struct{
double x,y;
}vector;
vector initVector(double r,double theta){
vector c;
c.x = r*cos(theta);
c.y = r*sin(theta);
return c;
}
vector addVector(vector a,vector b){
vector c;
c.x = a.x + b.x;
c.y = a.y + b.y;
return c;
}
vector subtra... | add (u,v) (x,y) = (u+x,v+y)
minus (u,v) (x,y) = (u-x,v-y)
multByScalar k (x,y) = (k*x,k*y)
divByScalar (x,y) k = (x/k,y/k)
main = do
let vecA = (3.0,8.0)
let (r,theta) = (3,pi/12) :: (Double,Double)
let vecB = (r*(cos theta),r*(sin theta))
putStrLn $ "vecA = " ++ (show vecA)
putStrLn $ "vecB = " +... |
Translate the given C code snippet into Haskell without altering its behavior. | #include <stdio.h>
#include <math.h>
#define C 7
typedef struct { double x, y; } pt;
pt zero(void) { return (pt){ INFINITY, INFINITY }; }
int is_zero(pt p) { return p.x > 1e20 || p.x < -1e20; }
pt neg(pt p) { return (pt){ p.x, -p.y }; }
pt dbl(pt p) {
if (is_zero(p)) return p;
pt r;
double L = (3 * p.x * p.x)... | import Data.Monoid
import Control.Monad (guard)
import Test.QuickCheck (quickCheck)
|
Port the following code from C to Haskell with equivalent syntax and logic. | #include <stdio.h>
#include <math.h>
#define C 7
typedef struct { double x, y; } pt;
pt zero(void) { return (pt){ INFINITY, INFINITY }; }
int is_zero(pt p) { return p.x > 1e20 || p.x < -1e20; }
pt neg(pt p) { return (pt){ p.x, -p.y }; }
pt dbl(pt p) {
if (is_zero(p)) return p;
pt r;
double L = (3 * p.x * p.x)... | import Data.Monoid
import Control.Monad (guard)
import Test.QuickCheck (quickCheck)
|
Write the same code in Haskell as shown below in C. | #include <string.h>
#include <stdio.h>
#include <stdlib.h>
const char STX = '\002', ETX = '\003';
int compareStrings(const void *a, const void *b) {
char *aa = *(char **)a;
char *bb = *(char **)b;
return strcmp(aa, bb);
}
int bwt(const char *s, char r[]) {
int i, len = strlen(s) + 2;
char *ss, *s... |
import Data.List ((!!), find, sort, tails, transpose)
import Data.Maybe (fromJust)
import Text.Printf (printf)
newtype BWT a = BWT [Val a]
bwt :: Ord a => [a] -> BWT a
bwt xs = let n = length xs + 2
ys = transpose $ sort $ take n $ tails $ cycle $ pos xs
in BWT $ ys !! (n-1)
invBwt :: Or... |
Maintain the same structure and functionality when rewriting this code in Haskell. | #include <string.h>
#include <stdio.h>
#include <stdlib.h>
const char STX = '\002', ETX = '\003';
int compareStrings(const void *a, const void *b) {
char *aa = *(char **)a;
char *bb = *(char **)b;
return strcmp(aa, bb);
}
int bwt(const char *s, char r[]) {
int i, len = strlen(s) + 2;
char *ss, *s... |
import Data.List ((!!), find, sort, tails, transpose)
import Data.Maybe (fromJust)
import Text.Printf (printf)
newtype BWT a = BWT [Val a]
bwt :: Ord a => [a] -> BWT a
bwt xs = let n = length xs + 2
ys = transpose $ sort $ take n $ tails $ cycle $ pos xs
in BWT $ ys !! (n-1)
invBwt :: Or... |
Transform the following C implementation into Haskell, maintaining the same output and logic. | #include <stdbool.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int binomial(int n, int k) {
int num, denom, i;
if (n < 0 || k < 0 || n < k) return -1;
if (n == 0 || k == 0) return 1;
num = 1;
for (i = k + 1; i <= n; ++i) {
num = num * i;
}
denom = 1;
for (i =... | import Data.Ratio (Ratio, denominator, numerator, (%))
faulhaber :: Int -> Rational -> Rational
faulhaber p n =
sum $
zipWith ((*) . (n ^)) [1 ..] (faulhaberTriangle !! p)
faulhaberTriangle :: [[Rational]]
faulhaberTriangle =
tail $
scanl
( \rs n ->
let xs = zipWith ((*) . (n %)) [2 ..]... |
Rewrite this program in Haskell while keeping its functionality equivalent to the C version. | #include <stdio.h>
#define MAX_N 33
#define BRANCH 4
typedef unsigned long long xint;
#define FMT "llu"
xint rooted[MAX_N] = {1, 1, 0};
xint unrooted[MAX_N] = {1, 1, 0};
xint choose(xint m, xint k)
{
xint i, r;
if (k == 1) return m;
for (r = m, i = 1; i < k; i++)
r = r * (m + i) / (i + 1);
return r;
}
... |
a `nmul` n = map (*n) a
a `ndiv` n = map (`div` n) a
instance (Integral a) => Num [a] where
(+) = zipWith (+)
negate = map negate
a * b = foldr f undefined b where
f x z = (a `nmul` x) + (0 : z)
abs _ = undefined
signum _ = undefined
fromInteger n = fromInteger n : repeat 0
repl a n = concatMap (: r... |
Produce a functionally identical Haskell code for the snippet given in C. | #include <stdio.h>
#define MAX_N 33
#define BRANCH 4
typedef unsigned long long xint;
#define FMT "llu"
xint rooted[MAX_N] = {1, 1, 0};
xint unrooted[MAX_N] = {1, 1, 0};
xint choose(xint m, xint k)
{
xint i, r;
if (k == 1) return m;
for (r = m, i = 1; i < k; i++)
r = r * (m + i) / (i + 1);
return r;
}
... |
a `nmul` n = map (*n) a
a `ndiv` n = map (`div` n) a
instance (Integral a) => Num [a] where
(+) = zipWith (+)
negate = map negate
a * b = foldr f undefined b where
f x z = (a `nmul` x) + (0 : z)
abs _ = undefined
signum _ = undefined
fromInteger n = fromInteger n : repeat 0
repl a n = concatMap (: r... |
Port the provided C code into Haskell while preserving the original functionality. | #include <stdbool.h>
#include <stdio.h>
#include <stdlib.h>
int binomial(int n, int k) {
int num, denom, i;
if (n < 0 || k < 0 || n < k) return -1;
if (n == 0 || k == 0) return 1;
num = 1;
for (i = k + 1; i <= n; ++i) {
num = num * i;
}
denom = 1;
for (i = 2; i <= n - k; ++i)... | import Data.Ratio ((%), numerator, denominator)
import Data.List (intercalate, transpose)
import Data.Bifunctor (bimap)
import Data.Char (isSpace)
import Data.Monoid ((<>))
import Data.Bool (bool)
faulhaber :: [[Rational]]
faulhaber =
tail $
scanl
(\rs n ->
let xs = zipWith ((*) . (n %)) [2 ..] rs
... |
Rewrite this program in Haskell while keeping its functionality equivalent to the C version. | #include <ldap.h>
char *name, *password;
...
LDAP *ld = ldap_init("ldap.somewhere.com", 389);
ldap_simple_bind_s(ld, name, password);
LDAPMessage **result;
ldap_search_s(ld, "dc=somewhere,dc=com", LDAP_SCOPE_SUBTREE,
"(&(objectclass=person)(|(cn=joe*)(cn=shmoe*)))",
NULL,
0,
result);
ldap_msgfree(*resul... |
module Main (main) where
import Data.Foldable (for_)
import qualified Data.Text.Encoding as Text (encodeUtf8)
import Ldap.Client (Attr(..), Filter(..))
import qualified Ldap.Client as Ldap (Dn(..), Host(..), search, with, typesOnly)
main :: IO ()
main = do
entries <- Ldap.with (Ldap.Plain "l... |
Change the programming language of this snippet from C to Haskell without modifying what it does. | #include <assert.h>
#include <stdbool.h>
#include <stdio.h>
typedef unsigned char byte;
struct Transition {
byte a, b;
unsigned int c;
} transitions[100];
void init() {
int i, j;
for (i = 0; i < 10; i++) {
for (j = 0; j < 10; j++) {
int idx = i * 10 + j;
transitions[id... | import Data.List (group, sort)
import Text.Printf (printf)
import Data.Numbers.Primes (primes)
freq :: [(Int, Int)] -> Float
freq xs = realToFrac (length xs) / 100
line :: [(Int, Int)] -> IO ()
line t@((n1, n2):xs) = printf "%d -> %d count: %5d frequency: %2.2f %%\n" n1 n2 (length t) (freq t)
main :: IO ()
main = m... |
Convert this C block to Haskell, preserving its control flow and logic. | #include <stdio.h>
#include <stdlib.h>
typedef unsigned int uint;
typedef unsigned long long tree;
#define B(x) (1ULL<<(x))
tree *list = 0;
uint cap = 0, len = 0;
uint offset[32] = {0, 1, 0};
void append(tree t)
{
if (len == cap) {
cap = cap ? cap*2 : 2;
list = realloc(list, cap*sizeof(tree));
}
list[len++] =... |
parts :: Int -> [[(Int, Int)]]
parts n = f n 1
where
f n x
| n == 0 = [[]]
| x > n = []
| otherwise =
f n (x + 1) ++
concatMap
(\c -> map ((c, x) :) (f (n - c * x) (x + 1)))
[1 .. n `div` x]
pick :: Int -> [String] -> [String]
pick _ [] = []
pick 0 _ = [""]... |
Write the same code in Haskell as shown below in C. | #include <stdio.h>
#include <limits.h>
typedef unsigned long long ull;
#define N (sizeof(ull) * CHAR_BIT)
#define B(x) (1ULL << (x))
void evolve(ull state, int rule)
{
int i, p, q, b;
for (p = 0; p < 10; p++) {
for (b = 0, q = 8; q--; ) {
ull st = state;
b |= (st&1) << q;
for (state = i = 0; i < N; i++... | import CellularAutomata (fromList, rule, runCA)
import Control.Comonad
import Data.List (unfoldr)
rnd = fromBits <$> unfoldr (pure . splitAt 8) bits
where
size = 80
bits =
extract
<$> runCA
(rule 30)
(fromList (1 : replicate size 0))
fromBits = foldl ((+) . (2 *)) 0
|
Convert this C block to Haskell, preserving its control flow and logic. | #include <stdbool.h>
#include <stdio.h>
#include <stdlib.h>
#define LUCKY_SIZE 60000
int luckyOdd[LUCKY_SIZE];
int luckyEven[LUCKY_SIZE];
void compactLucky(int luckyArray[]) {
int i, j, k;
for (i = 0; i < LUCKY_SIZE; i++) {
if (luckyArray[i] == 0) {
j = i;
break;
}
... | import System.Environment
import Text.Regex.Posix
data Lucky = Lucky | EvenLucky
helpMessage :: IO ()
helpMessage = do
putStrLn " what is displayed (on a single line)"
putStrLn " argument(s) (optional verbiage is encouraged)"
putStrLn "======================|========... |
Change the programming language of this snippet from C to Haskell without modifying what it does. | #include <math.h>
#include <stdio.h>
#include <string.h>
int find(char *s, char c) {
for (char *i = s; *i != 0; i++) {
if (*i == c) {
return i - s;
}
}
return -1;
}
void reverse(char *b, char *e) {
for (e--; b < e; b++, e--) {
char t = *b;
*b = *e;
*... | import Data.Char (chr, digitToInt, intToDigit, isDigit, ord)
import Data.Complex (Complex (..), imagPart, realPart)
import Data.List (delete, elemIndex)
import Data.Maybe (fromMaybe)
base :: Complex Float
base = 0 :+ 2
quotRemPositive :: Int -> Int -> (Int, Int)
quotRemPositive a b
| r < 0 = (1 + q, floor (realPart... |
Please provide an equivalent version of this C code in Haskell. |
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <string.h>
#include <time.h>
#define NMAX 10000000
double mean(double* values, int n)
{
int i;
double s = 0;
for ( i = 0; i < n; i++ )
s += values[i];
return s / n;
}
double stddev(double* values, int n)
{
int i;
d... | import Data.Map (Map, empty, insert, findWithDefault, toList)
import Data.Maybe (fromMaybe)
import Text.Printf (printf)
import Data.Function (on)
import Data.List (sort, maximumBy, minimumBy)
import Control.Monad.Random (RandomGen, Rand, evalRandIO, getRandomR)
import Control.Monad (replicateM)
getNorm :: RandomGen g... |
Please provide an equivalent version of this C code in Haskell. | #include <stdbool.h>
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
__int128 imax(__int128 a, __int128 b) {
if (a > b) {
return a;
}
return b;
}
__int128 ipow(__int128 b, __int128 n) {
__int128 res;
if (n == 0) {
return 1;
}
if (n == 1) {
return b;
}... | import Data.Bifunctor (bimap)
import Data.List (find)
import Data.Maybe (isJust)
b10 :: Integral a => a -> Integer
b10 n = read (digitMatch rems sums) :: Integer
where
(_, rems, _, Just (_, sums)) =
until
(\(_, _, _, mb) -> isJust mb)
( \(e, rems, ms, _) ->
let m = rem (10 ^ e... |
Generate an equivalent Haskell version of this C code. | #include<stdlib.h>
#include<ctype.h>
#include<stdio.h>
int** oddMagicSquare(int n) {
if (n < 3 || n % 2 == 0)
return NULL;
int value = 0;
int squareSize = n * n;
int c = n / 2, r = 0,i;
int** result = (int**)malloc(n*sizeof(int*));
for(i=0;i<n... | import qualified Data.Map.Strict as M
import Data.List (transpose, intercalate)
import Data.Maybe (fromJust, isJust)
import Control.Monad (forM_)
import Data.Monoid ((<>))
magic :: Int -> [[Int]]
magic n = mapAsTable ((4 * n) + 2) (hiResMap n)
hiResMap :: Int -> M.Map (Int, Int) Int
hiResMap n =
let mapLux = luxMa... |
Ensure the translated Haskell code behaves exactly like the original C snippet. | #include "stdio.h"
#include "stdlib.h"
#include "stdbool.h"
#include "string.h"
struct int_a {
int *ptr;
size_t size;
};
struct int_a divisors(int n) {
int *divs, *divs2, *out;
int i, j, c1 = 0, c2 = 0;
struct int_a array;
divs = malloc(n * sizeof(int) / 2);
divs2 = malloc(n * sizeof(int)... | weirds :: [Int]
weirds = filter abundantNotSemiperfect [1 ..]
abundantNotSemiperfect :: Int -> Bool
abundantNotSemiperfect n =
let ds = descProperDivisors n
d = sum ds - n
in 0 < d && not (hasSum d ds)
hasSum :: Int -> [Int] -> Bool
hasSum _ [] = False
hasSum n (x:xs)
| n < x = hasSum n xs
| otherwise =... |
Maintain the same structure and functionality when rewriting this code in Haskell. | #include <stdlib.h>
#include <stdio.h>
#include <string.h>
enum { MAX_ROWS=14, MAX_NAMES=20, NAME_SZ=80 };
char *Lines[MAX_ROWS] = {
" +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+",
" | ID |",
" +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+",
" |QR| ... | import Text.ParserCombinators.ReadP
import Control.Monad (guard)
data Field a = Field { fieldName :: String
, fieldSize :: Int
, fieldValue :: Maybe a}
instance Show a => Show (Field a) where
show (Field n s a) = case a of
Nothing -> n ++ "\t" ++ show s
Just x -> n ... |
Rewrite the snippet below in Haskell so it works the same as the original C code. | #include <math.h>
#include <stdbool.h>
#include <stdint.h>
#include <stdio.h>
#define LIMIT 15
int smallPrimes[LIMIT];
static void sieve() {
int i = 2, j;
int p = 5;
smallPrimes[0] = 2;
smallPrimes[1] = 3;
while (i < LIMIT) {
for (j = 0; j < i; j++) {
if (smallPrimes[j] * sma... | import Control.Monad (guard)
import Math.NumberTheory.ArithmeticFunctions (divisorCount)
import Math.NumberTheory.Primes (Prime, unPrime)
import Math.NumberTheory.Primes.Testing (isPrime)
calc :: Integer -> [(Integer, Integer)]
calc n = ... |
Convert this C block to Haskell, preserving its control flow and logic. | #include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define TRUE 1
#define FALSE 0
typedef int bool;
typedef struct {
int x, y;
} pair;
int* example = NULL;
int exampleLen = 0;
void reverse(int s[], int len) {
int i, j, t;
for (i = 0, j = len - 1; i < j; ++i, --j) {
t = s[i];
s[i... | import Data.List (union)
total [] = []
total (x:xs) = brauer (x:xs) `union` total xs
brauer [] = []
brauer (x:xs) = map (+ x) (x:xs)
chains _ 1 = [[1]]
chains sums n = go [[1]]
where
go ch = let next = ch >>= step
complete = filter ((== n) . head) next
in if null complete then go ... |
Port the provided C code into Haskell while preserving the original functionality. | #include <stdio.h>
#include <ctype.h>
#include <stdlib.h>
int main(int argc, char **argv)
{
typedef enum State { READY, WAITING, REFUND, DISPENSE, COLLECT, QUIT } State;
typedef struct statechange {
const int in;
const State out;
} statechange;
#define MAXINPUTS 3
typedef struct FSM {
const State... | import System.Exit
import Data.Maybe
import Control.Monad
import Data.List
import System.IO
type Name = String
type Sequence = String
type State = String
data Trigger = Trigger { name :: Name
, tseq :: Sequence } deriving (Eq)
instance Show Trigger where
show (Trigger name tseq) = name ++ "(... |
Convert this C block to Haskell, preserving its control flow and logic. | # define NUMBER_OF_POINTS 100000
# define NUMBER_OF_CLUSTERS 11
# define MAXIMUM_ITERATIONS 100
# define RADIUS 10.0
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
typedef struct {
double x;
double y;
int group;
} POINT;
POINT * gen_xy(int num_pts, double radius)
{
int i;
double ang, r;
POINT... |
module KMeans where
import Control.Applicative
import Control.Monad.Random
import Data.List (minimumBy, genericLength, transpose)
import Data.Ord (comparing)
import qualified Data.Map.Strict as M
type Vec = [Float]
type Cluster = [Vec]
kMeansIteration :: [Vec] -> [Vec] -> [Cluster]
kMeansIteration pts = cluster... |
Convert this C block to Haskell, preserving its control flow and logic. | #include <glib.h>
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
guchar* sha256_merkle_tree(FILE* in, size_t block_size) {
gchar* buffer = g_malloc(block_size);
GPtrArray* hashes = g_ptr_array_new_with_free_func(g_free);
gssize digest_length = g_checksum_type_get_length(G_CHECKSUM_SHA256);
... |
import Control.Monad (mfilter)
import Crypto.Hash.SHA256 (hash)
import qualified Data.ByteString as B
import Data.ByteString.Builder (byteStringHex, char7, hPutBuilder)
import Data.Functor ((<&>))
import Data.Maybe (listToMaybe)
import Data.Strict.Tuple (Pair(..))
import qualified Data.Strict.Tuple as T
import System... |
Generate a Haskell translation of this C snippet without changing its computational steps. | #include <stdint.h>
#include <stdlib.h>
#include <stdio.h>
#include <time.h>
#include <gmp.h>
mpz_t* partition(uint64_t n) {
mpz_t *pn = (mpz_t *)malloc((n + 2) * sizeof(mpz_t));
mpz_init_set_ui(pn[0], 1);
mpz_init_set_ui(pn[1], 1);
for (uint64_t i = 2; i < n + 2; i ++) {
mpz_init(pn[i]);
for (uint64_t k = 1, ... |
data Memo a = Node a (Memo a) (Memo a)
deriving (Functor)
memo :: Integral a => Memo p -> a -> p
memo (Node a l r) n
| n == 0 = a
| odd n = memo l (n `div` 2)
| otherwise = memo r (n `div` 2 - 1)
nats :: Memo Int
nats =
Node
0
((+ 1) . (* 2) <$> nats)
((* 2) . (+ 1) <$> nats)
partitions... |
Port the following code from C to Haskell with equivalent syntax and logic. | #include <stdio.h>
#include <math.h>
#include <stdlib.h>
#include <stdint.h>
#include <time.h>
const uint8_t masks[8] = {1, 2, 4, 8, 16, 32, 64, 128};
#define half(n) ((int64_t)((n) - 1) >> 1)
#define divide(nm, d) ((uint64_t)((double)nm / (double)d))
int64_t countPrimes(uint64_t n) {
if (n < 9) return (n < 2) ... |
import Data.Time.Clock.POSIX ( getPOSIXTime )
import Data.Int ( Int64 )
import Data.Bits ( Bits( shiftL, shiftR ) )
data Memo a = EmptyNode | Node a (Memo a) (Memo a)
deriving Functor
memo :: Integral a => Memo p -> a -> p
memo (Node a l r) n
| n == 0 = a
| odd n = memo l (n `div` 2)
| otherwise = memo r... |
Write a version of this C function in Haskell with identical behavior. | #include <stdbool.h>
#include <stdio.h>
#include <stdint.h>
typedef uint64_t integer;
integer reverse(integer n) {
integer rev = 0;
while (n > 0) {
rev = rev * 10 + (n % 10);
n /= 10;
}
return rev;
}
typedef struct palgen_tag {
integer power;
integer next;
int digit;
b... | import Control.Monad (guard)
palindromic :: Int -> Bool
palindromic n = d == reverse d
where
d = show n
gapful :: Int -> Bool
gapful n = n `rem` firstLastDigit == 0
where
firstLastDigit = read [head asDigits, last asDigits]
asDigits = show n
result :: Int -> [Int]
result d = do
x <- [(d+100),(d+110)..]
... |
Preserve the algorithm and functionality while converting the code from C to Haskell. | #include <stdbool.h>
#include <stdio.h>
#include <stdint.h>
typedef uint64_t integer;
integer reverse(integer n) {
integer rev = 0;
while (n > 0) {
rev = rev * 10 + (n % 10);
n /= 10;
}
return rev;
}
typedef struct palgen_tag {
integer power;
integer next;
int digit;
b... | import Control.Monad (guard)
palindromic :: Int -> Bool
palindromic n = d == reverse d
where
d = show n
gapful :: Int -> Bool
gapful n = n `rem` firstLastDigit == 0
where
firstLastDigit = read [head asDigits, last asDigits]
asDigits = show n
result :: Int -> [Int]
result d = do
x <- [(d+100),(d+110)..]
... |
Change the following C code into Haskell without altering its purpose. | #include <stdio.h>
#include <stdlib.h>
#include <math.h>
int main(void) {
int nprimes = 1000000;
int nmax = ceil(nprimes*(log(nprimes)+log(log(nprimes))-0.9385));
int i, j, m, k; int *a;
k = (nmax-2)/2;
a = (int *)calloc(k + 1, sizeof(int));
for(i = 0; i <= k; i++)a[i] = 2*i... | import Data.List (intercalate, transpose)
import Data.List.Split (chunksOf)
import qualified Data.Set as S
import Text.Printf (printf)
sundaram :: Integral a => a -> [a]
sundaram n =
[ succ (2 * x)
| x <- [1 .. m],
x `S.notMember` excluded
]
where
m = div (pred n) 2
excluded =
S.fromLis... |
Convert the following code from C to Haskell, ensuring the logic remains intact. | #include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
#include <string.h>
bool *sieve(int limit) {
int i, p;
limit++;
bool *c = calloc(limit, sizeof(bool));
c[0] = true;
c[1] = true;
for (i = 4; i < limit; i += 2) c[i] = true;
p = 3;
while (true) {
int p2 = p * p;
... | import Data.Numbers.Primes (primes)
consecutives equiv = filter ((> 1) . length) . go []
where
go r [] = [r]
go [] (h : t) = go [h] t
go (y : ys) (h : t)
| y `equiv` h = go (h : y : ys) t
| otherwise = (y : ys) : go [h] t
maximumBy g (h : t) = foldr f h t
where
f r x = if g r < g x t... |
Write a version of this C function in Haskell with identical behavior. | #include <stdio.h>
void padovanN(int n, size_t t, int *p) {
int i, j;
if (n < 2 || t < 3) {
for (i = 0; i < t; ++i) p[i] = 1;
return;
}
padovanN(n-1, t, p);
for (i = n + 1; i < t; ++i) {
p[i] = 0;
for (j = i - 2; j >= i - n - 1; --j) p[i] += p[j];
}
}
int main()... | import Data.Bifunctor (second)
import Data.List (transpose, uncons, unfoldr)
padovans :: Int -> [Int]
padovans n
| 0 > n = []
| otherwise = unfoldr (recurrence n) $ take (succ n) xs
where
xs
| 3 > n = repeat 1
| otherwise = padovans $ pred n
recurrence :: Int -> [Int] -> Maybe (Int, [Int])
rec... |
Can you help me rewrite this code in Haskell instead of C, keeping it the same logically? | #include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
#include <locale.h>
#define LIMIT 5000000
typedef struct {
int x;
int y;
} pair;
int *primeSieve(int limit, int *length) {
int i, p, *primes;
int j, pc = 0;
limit++;
bool *c = calloc(limit, sizeof(bool));
c[0] = true;
c... | import Control.Monad (join)
import Data.Bifunctor (bimap)
import Data.List.Split (chunksOf)
import Data.Numbers.Primes (primes)
honakers :: [(Integer, Integer)]
honakers =
filter
(uncurry (==) . both sumDigits)
(zip [1 ..] primes)
main :: IO ()
main =
putStrLn "First Fifty:\n"
>> mapM_
(putSt... |
Keep all operations the same but rewrite the snippet in Haskell. | #include <stdio.h>
#include <math.h>
#define MAX_DIGITS 9
int digits[MAX_DIGITS];
void getDigits(int i) {
int ix = 0;
while (i > 0) {
digits[ix++] = i % 10;
i /= 10;
}
}
int main() {
int n, d, i, max, lastDigit, sum, dp;
int powers[10] = {0, 1, 4, 9, 16, 25, 36, 49, 64, 81};
... | import Data.List (sort)
ownDigitsPowerSums :: Int -> [Int]
ownDigitsPowerSums n = sort (ns >>= go)
where
ns = combsWithRep n [0 .. 9]
go xs
| digitsMatch m xs = [m]
| otherwise = []
where
m = foldr ((+) . (^ n)) 0 xs
digitsMatch :: Show a => a -> [Int] -> Bool
digitsMatch n ds =
... |
Rewrite this program in Haskell while keeping its functionality equivalent to the C version. | #include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
#include <stdint.h>
#include <locale.h>
bool *sieve(uint64_t limit) {
uint64_t i, p;
limit++;
bool *c = calloc(limit, sizeof(bool));
c[0] = true;
c[1] = true;
for (i = 4; i < limit; i += 2) c[i] = true;
p = 3;
while (tru... | import Data.Numbers.Primes (primes)
import Data.List (sort)
ormistons :: [(Integer, Integer, Integer)]
ormistons =
concat $ zipWith3
(\(dx, x) (dy, y) (dz, z)
-> [(x, y, z) | dx == dy && dx == dz])
primeDigits
(tail primeDigits)
(drop 2 primeDigits)
primeDigits :: [(Integer, I... |
Convert this C snippet to Haskell and keep its semantics consistent. | #include <stdio.h>
#include <stdint.h>
#include <stdbool.h>
typedef struct {
uint16_t year;
uint8_t month;
uint8_t day;
} Date;
bool leap(uint16_t year) {
return year%4==0 && (year%100!=0 || year%400==0);
}
const char *weekday(Date date) {
static const uint8_t leapdoom[] = {4,1,7,2,4,6,4,1,5,3,7... | import Text.Printf
data Date = Date {year :: Int, month :: Int, day :: Int}
instance Show Date where
show Date {year = y, month = m, day = d} =
printf "%4d-%02d-%02d" y m d
leap :: Int -> Bool
leap year =
year `mod` 4 == 0
&& (year `mod` 100 /= 0 || year `mod` 400 == 0)
weekday :: Date -> Int
weekday Da... |
Please provide an equivalent version of this C code in Haskell. | #include <stdio.h>
#include <stdint.h>
#include <stdbool.h>
typedef struct {
uint16_t year;
uint8_t month;
uint8_t day;
} Date;
bool leap(uint16_t year) {
return year%4==0 && (year%100!=0 || year%400==0);
}
const char *weekday(Date date) {
static const uint8_t leapdoom[] = {4,1,7,2,4,6,4,1,5,3,7... | import Text.Printf
data Date = Date {year :: Int, month :: Int, day :: Int}
instance Show Date where
show Date {year = y, month = m, day = d} =
printf "%4d-%02d-%02d" y m d
leap :: Int -> Bool
leap year =
year `mod` 4 == 0
&& (year `mod` 100 /= 0 || year `mod` 400 == 0)
weekday :: Date -> Int
weekday Da... |
Keep all operations the same but rewrite the snippet in Haskell. |
#include <math.h>
int gjinv (double *a, int n, double *b)
{
int i, j, k, p;
double f, g, tol;
if (n < 1) return -1;
f = 0.;
for (i = 0; i < n; ++i) {
for (j = 0; j < n; ++j) {
g = a[j+i*n];
f += g * g;
}
}
f = sqrt(f);
tol = f * 2.2204460492503131e-016;
for (i = 0; i < n; ++i) {
for (j = 0; ... | isMatrix xs = null xs || all ((== (length.head $ xs)).length) xs
isSquareMatrix xs = null xs || all ((== (length xs)).length) xs
mult:: Num a => [[a]] -> [[a]] -> [[a]]
mult uss vss = map ((\xs -> if null xs then [] else foldl1 (zipWith (+)) xs). zipWith (\vs u -> map (u*) vs) vss) uss
matI::(Num a) => Int -> [[a]]
... |
Convert this C snippet to Haskell and keep its semantics consistent. |
#include <math.h>
int gjinv (double *a, int n, double *b)
{
int i, j, k, p;
double f, g, tol;
if (n < 1) return -1;
f = 0.;
for (i = 0; i < n; ++i) {
for (j = 0; j < n; ++j) {
g = a[j+i*n];
f += g * g;
}
}
f = sqrt(f);
tol = f * 2.2204460492503131e-016;
for (i = 0; i < n; ++i) {
for (j = 0; ... | isMatrix xs = null xs || all ((== (length.head $ xs)).length) xs
isSquareMatrix xs = null xs || all ((== (length xs)).length) xs
mult:: Num a => [[a]] -> [[a]] -> [[a]]
mult uss vss = map ((\xs -> if null xs then [] else foldl1 (zipWith (+)) xs). zipWith (\vs u -> map (u*) vs) vss) uss
matI::(Num a) => Int -> [[a]]
... |
Produce a language-to-language conversion: from C to Haskell, same semantics. | #include <locale.h>
#include <stdbool.h>
#include <stdio.h>
#include <time.h>
bool colorful(int n) {
if (n < 0 || n > 98765432)
return false;
int digit_count[10] = {};
int digits[8] = {};
int num_digits = 0;
for (int m = n; m > 0; m /= 10) {
int d = m % 10;
if (n > 9 &&... | import Data.List ( nub )
import Data.List.Split ( divvy )
import Data.Char ( digitToInt )
isColourful :: Integer -> Bool
isColourful n
|n >= 0 && n <= 10 = True
|n > 10 && n < 100 = ((length s) == (length $ nub s)) &&
(not $ any (\c -> elem c "01") s)
|n >= 100 = ((length s) == (length $ nub s)) && (n... |
Rewrite the snippet below in Haskell so it works the same as the original C code. | #include <locale.h>
#include <stdbool.h>
#include <stdio.h>
#include <time.h>
bool colorful(int n) {
if (n < 0 || n > 98765432)
return false;
int digit_count[10] = {};
int digits[8] = {};
int num_digits = 0;
for (int m = n; m > 0; m /= 10) {
int d = m % 10;
if (n > 9 &&... | import Data.List ( nub )
import Data.List.Split ( divvy )
import Data.Char ( digitToInt )
isColourful :: Integer -> Bool
isColourful n
|n >= 0 && n <= 10 = True
|n > 10 && n < 100 = ((length s) == (length $ nub s)) &&
(not $ any (\c -> elem c "01") s)
|n >= 100 = ((length s) == (length $ nub s)) && (n... |
Keep all operations the same but rewrite the snippet in Haskell. | #include <stdio.h>
#include <math.h>
#include <string.h>
#include <stdlib.h>
#include <time.h>
#define TRUE 1
#define FALSE 0
typedef int bool;
char grid[8][8];
void placeKings() {
int r1, r2, c1, c2;
for (;;) {
r1 = rand() % 8;
c1 = rand() % 8;
r2 = rand() % 8;
c2 = rand() %... |
module RandomChess
( placeKings
, placePawns
, placeRemaining
, emptyBoard
, toFen
, ChessBoard
, Square (..)
, BoardState (..)
, getBoard
)
where
import Control.Monad.State (State, get, gets, put)
import Data.List (find, sortBy)
import System.Random (Random, RandomGen, StdGen, random, randomR)
type Pos = (Char, In... |
Maintain the same structure and functionality when rewriting this code in Haskell. | #include <stdio.h>
#include <locale.h>
int divisorCount(int n) {
int i, j, count = 0, k = !(n%2) ? 1 : 2;
for (i = 1; i*i <= n; i += k) {
if (!(n%i)) {
++count;
j = n/i;
if (j != i) ++count;
}
}
return count;
}
int main() {
int i, numbers50[50], ... | import Data.List (group, intercalate, transpose)
import Data.List.Split (chunksOf)
import Data.Numbers.Primes ( primeFactors )
import Text.Printf (printf)
oeisA111398 :: [Integer]
oeisA111398 = 1 : [n | n <- [1..], 8 == length (divisors n)]
divisors :: Integer -> [Integer]
divisors =
foldr
(flip ((<*>) . fm... |
Maintain the same structure and functionality when rewriting this code in Haskell. | #include <stdio.h>
#include <stdint.h>
typedef uint64_t u64;
void primeFactors(u64 n, u64 *factors, int *length) {
if (n < 2) return;
int count = 0;
int inc[8] = {4, 2, 4, 2, 4, 6, 2, 6};
while (!(n%2)) {
factors[count++] = 2;
n /= 2;
}
while (!(n%3)) {
factors[count++]... | import Control.Monad (forM_)
import Data.List (intercalate)
import Data.List.Split (chunksOf)
import Math.NumberTheory.Primes (factorise, unPrime)
import Text.Printf (printf)
arithderiv_ :: Integer -> Integer
arithderiv_ 0 = 0
arithderiv_ n = foldr step 0 $ factorise n
where step (p, v) s = s + n `quot` unPrime p *... |
Write a version of this C function in Haskell with identical behavior. | #include <stdbool.h>
#include <stdio.h>
#include <string.h>
#define MAX 100
void sieve(bool *prime, int max) {
memset(prime, true, max+1);
prime[0] = prime[1] = false;
for (int p=2; p*p<=max; p++)
for (int c=p*p; c<=max; c+=p)
prime[c] = false;
}
int lo_fac(bool *prime, int n) {... | import Data.List (intercalate, transpose)
import Data.List.Split (chunksOf)
import Data.Numbers.Primes (primeFactors)
import Text.Printf (printf)
oeisA066048 :: [Integer]
oeisA066048 = 1 : fmap f [2 ..]
where
f = ((*) . head <*> last) . primeFactors
main :: IO ()
main = putStrLn $
table " " $ (chunksOf 1... |
Generate an equivalent Haskell version of this C code. | #include <stdio.h>
#include <stdlib.h>
#include <time.h>
void fatal(const char* message) {
fprintf(stderr, "%s\n", message);
exit(1);
}
void* xmalloc(size_t n) {
void* ptr = malloc(n);
if (ptr == NULL)
fatal("Out of memory");
return ptr;
}
typedef struct node_tag {
int item;
struc... |
import Data.Foldable
data DList a = End | Elem { prev :: DList a
, elt :: a
, next :: DList a }
mkDList :: Foldable t => t a -> DList a
mkDList = go End . toList
where go _ [] = End
go prev (x:xs) = current
where current = Elem prev x ... |
Translate this program into Haskell but keep the logic exactly as in C. | #include <stdio.h>
#include <stdlib.h>
#include <time.h>
void fatal(const char* message) {
fprintf(stderr, "%s\n", message);
exit(1);
}
void* xmalloc(size_t n) {
void* ptr = malloc(n);
if (ptr == NULL)
fatal("Out of memory");
return ptr;
}
typedef struct node_tag {
int item;
struc... |
import Data.Foldable
data DList a = End | Elem { prev :: DList a
, elt :: a
, next :: DList a }
mkDList :: Foldable t => t a -> DList a
mkDList = go End . toList
where go _ [] = End
go prev (x:xs) = current
where current = Elem prev x ... |
Port the following code from C to Haskell with equivalent syntax and logic. | #include <stdio.h>
#include "achain.c"
typedef struct {double u, v;} cplx;
inline cplx c_mul(cplx a, cplx b)
{
cplx c;
c.u = a.u * b.u - a.v * b.v;
c.v = a.u * b.v + a.v * b.u;
return c;
}
cplx chain_expo(cplx x, int n)
{
int i, j, k, l, e[32];
cplx v[32];
l = seq(n, 0, e);
puts("Exponents:");
for (i =... | dichotomicChain :: Integral a => a -> [a]
dichotomicChain n
| n == 3 = [3, 2, 1]
| n == 2 ^ log2 n = takeWhile (> 0) $ iterate (`div` 2) n
| otherwise = let k = n `div` (2 ^ ((log2 n + 1) `div` 2))
in chain n k
where
chain n1 n2
| n2 <= 1 = dichotomicChain n1
| otherwise = case... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.