Instruction stringlengths 45 106 | input_code stringlengths 1 13.7k | output_code stringlengths 1 13.7k |
|---|---|---|
Generate an equivalent Haskell version of this C code. | #include <stdio.h>
#include <stdlib.h>
#include <string.h>
struct Wheel {
char *seq;
int len;
int pos;
};
struct Wheel *create(char *seq) {
struct Wheel *w = malloc(sizeof(struct Wheel));
if (w == NULL) {
return NULL;
}
w->seq = seq;
w->len = strlen(seq);
w->pos = 0;
... | import Data.Char (isDigit)
import Data.List (mapAccumL)
import qualified Data.Map.Strict as M
import Data.Maybe (fromMaybe)
clockWorkTick ::
M.Map Char String ->
(M.Map Char String, Char)
clockWorkTick = flip click 'A'
where
click wheels name
| isDigit name = (wheels, name)
| otherwise =
... |
Please provide an equivalent version of this C code in Haskell. | #include <stdio.h>
#include <stdlib.h>
#include <string.h>
struct Wheel {
char *seq;
int len;
int pos;
};
struct Wheel *create(char *seq) {
struct Wheel *w = malloc(sizeof(struct Wheel));
if (w == NULL) {
return NULL;
}
w->seq = seq;
w->len = strlen(seq);
w->pos = 0;
... | import Data.Char (isDigit)
import Data.List (mapAccumL)
import qualified Data.Map.Strict as M
import Data.Maybe (fromMaybe)
clockWorkTick ::
M.Map Char String ->
(M.Map Char String, Char)
clockWorkTick = flip click 'A'
where
click wheels name
| isDigit name = (wheels, name)
| otherwise =
... |
Convert this C block to Haskell, preserving its control flow and logic. |
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <curl/curl.h>
#include "wren.h"
struct MemoryStruct {
char *memory;
size_t size;
};
static size_t WriteMemoryCallback(void *contents, size_t size, size_t nmemb, void *userp) {
size_t realsize = size * nmemb;
struct MemoryStruct *m... | import Network.HTTP
import Text.Parsec
data YahooSearchItem = YahooSearchItem {
itemUrl, itemTitle, itemContent :: String }
data YahooSearch = YahooSearch {
searchQuery :: String,
searchPage :: Int,
searchItems :: [YahooSearchItem] }
yahooUrl = "http://search.yahoo.com/search?p="
yahoo :: Stri... |
Port the following code from C to Haskell with equivalent syntax and logic. | #include<stdio.h>
#include<math.h>
typedef struct{
double x,y;
}point;
double distance(point p1,point p2)
{
return sqrt((p1.x-p2.x)*(p1.x-p2.x)+(p1.y-p2.y)*(p1.y-p2.y));
}
void findCircles(point p1,point p2,double radius)
{
double separation = distance(p1,p2),mirrorDistance;
if(separation == 0.0)
{
radiu... | add (a, b) (x, y) = (a + x, b + y)
sub (a, b) (x, y) = (a - x, b - y)
magSqr (a, b) = (a ^^ 2) + (b ^^ 2)
mag a = sqrt $ magSqr a
mul (a, b) c = (a * c, b * c)
div2 (a, b) c = (a / c, b / c)
perp (a, b) = (negate b, a)
norm a = a `div2` mag a
circlePoints :: (Ord a, Floating a... |
Change the following C code into Haskell without altering its purpose. | #include<stdio.h>
#include<math.h>
typedef struct{
double x,y;
}point;
double distance(point p1,point p2)
{
return sqrt((p1.x-p2.x)*(p1.x-p2.x)+(p1.y-p2.y)*(p1.y-p2.y));
}
void findCircles(point p1,point p2,double radius)
{
double separation = distance(p1,p2),mirrorDistance;
if(separation == 0.0)
{
radiu... | add (a, b) (x, y) = (a + x, b + y)
sub (a, b) (x, y) = (a - x, b - y)
magSqr (a, b) = (a ^^ 2) + (b ^^ 2)
mag a = sqrt $ magSqr a
mul (a, b) c = (a * c, b * c)
div2 (a, b) c = (a / c, b / c)
perp (a, b) = (negate b, a)
norm a = a `div2` mag a
circlePoints :: (Ord a, Floating a... |
Convert this C block to Haskell, preserving its control flow and logic. | #include <stdio.h>
#include <stdlib.h>
#include <stdint.h>
#include <math.h>
typedef uint64_t xint;
typedef unsigned long long ull;
xint tens[20];
inline xint max(xint a, xint b) { return a > b ? a : b; }
inline xint min(xint a, xint b) { return a < b ? a : b; }
inline int ndigits(xint x)
{
int n = 0;
while (x) n+... | import Data.List (sort)
import Control.Arrow ((&&&))
vampires :: [Int]
vampires = filter (not . null . fangs) [1 ..]
fangs :: Int -> [(Int, Int)]
fangs n
| odd w = []
| otherwise = ((,) <*> quot n) <$> filter isfang (integerFactors n)
where
ndigit :: Int -> Int
ndigit 0 = 0
ndigit n = 1 + ndigit (q... |
Rewrite this program in Haskell while keeping its functionality equivalent to the C version. | #include <stdio.h>
#include <stdlib.h>
#include <stdint.h>
#define SIM_N 5
#define PRINT_DISCARDED 1
#define min(x,y) ((x<y)?(x):(y))
typedef uint8_t card_t;
unsigned int rand_n(unsigned int n) {
unsigned int out, mask = 1;
while (mask < n) mask = mask<<1 | 1;
do {
out =... | import System.Random (randomRIO)
import Data.List (partition)
import Data.Monoid ((<>))
main :: IO [Int]
main = do
ns <- knuthShuffle [1 .. 52]
let (rs_, bs_, discards) = threeStacks (rb <$> ns)
nSwap <- randomRIO (1, min (length rs_) (length bs_))
let (rs, bs) = exchange nSwap rs_ bs_
let rr... |
Translate the given C code snippet into Haskell without altering its behavior. | #include <stdio.h>
#include <stdlib.h>
#include <stdint.h>
#define SIM_N 5
#define PRINT_DISCARDED 1
#define min(x,y) ((x<y)?(x):(y))
typedef uint8_t card_t;
unsigned int rand_n(unsigned int n) {
unsigned int out, mask = 1;
while (mask < n) mask = mask<<1 | 1;
do {
out =... | import System.Random (randomRIO)
import Data.List (partition)
import Data.Monoid ((<>))
main :: IO [Int]
main = do
ns <- knuthShuffle [1 .. 52]
let (rs_, bs_, discards) = threeStacks (rb <$> ns)
nSwap <- randomRIO (1, min (length rs_) (length bs_))
let (rs, bs) = exchange nSwap rs_ bs_
let rr... |
Produce a functionally identical Haskell code for the snippet given in C. | #include <stdio.h>
#include <ctype.h>
#include <string.h>
#include <stdlib.h>
#define TRUE 1
#define FALSE 0
#define FACES "23456789tjqka"
#define SUITS "shdc"
typedef int bool;
typedef struct {
int face;
char suit;
} card;
card cards[5];
int compare_card(const void *a, const void *b) {
card c1 = *(... |
import Data.Function (on)
import Data.List (group, nub, any, sort, sortBy)
import Data.Maybe (mapMaybe)
import Text.Read (readMaybe)
data Suit = Club | Diamond | Spade | Heart deriving (Show, Eq)
data Rank = Ace | Two | Three | Four | Five | Six | Seven
| Eight | Nine | Ten | Jack | Queen | Kin... |
Write a version of this C function in Haskell with identical behavior. | #include <stdio.h>
#include <ctype.h>
#include <string.h>
#include <stdlib.h>
#define TRUE 1
#define FALSE 0
#define FACES "23456789tjqka"
#define SUITS "shdc"
typedef int bool;
typedef struct {
int face;
char suit;
} card;
card cards[5];
int compare_card(const void *a, const void *b) {
card c1 = *(... |
import Data.Function (on)
import Data.List (group, nub, any, sort, sortBy)
import Data.Maybe (mapMaybe)
import Text.Read (readMaybe)
data Suit = Club | Diamond | Spade | Heart deriving (Show, Eq)
data Rank = Ace | Two | Three | Four | Five | Six | Seven
| Eight | Nine | Ten | Jack | Queen | Kin... |
Rewrite this program in Haskell while keeping its functionality equivalent to the C version. | #include <stdio.h>
int main(void)
{
puts( "%!PS-Adobe-3.0 EPSF\n"
"%%BoundingBox: -10 -10 400 565\n"
"/a{0 0 moveto 0 .4 translate 0 0 lineto stroke -1 1 scale}def\n"
"/b{a 90 rotate}def");
char i;
for (i = 'c'; i <= 'z'; i++)
printf("/%c{%c %c}def\n", i, i-1, i-2);
puts("0 setlinewidth z showpage\n%%EOF... | import Data.List (unfoldr)
import Data.Bool (bool)
import Data.Semigroup (Sum(..), Min(..), Max(..))
import System.IO (writeFile)
fibonacciWord :: a -> a -> [[a]]
fibonacciWord a b = unfoldr (\(a,b) -> Just (a, (b, a <> b))) ([a], [b])
toPath :: [Bool] -> ((Min Int, Max Int, Min Int, Max Int), String)
toPath = foldMa... |
Translate this program into Haskell but keep the logic exactly as in C. | #include <stdio.h>
#include <stdlib.h>
#include <time.h>
#define SEQLEN 3
int getseq(char *s)
{
int r = 0;
int i = 1 << (SEQLEN - 1);
while (*s && i) {
switch (*s++) {
case 'H':
case 'h':
r |= i;
break;
case 'T':
case... | import qualified Data.List as L
import System.IO
import System.Random
data CoinToss = H | T deriving (Read, Show, Eq)
parseToss :: String -> [CoinToss]
parseToss [] = []
parseToss (s:sx)
| s == 'h' || s == 'H' = H : parseToss sx
| s == 't' || s == 'T' = T : parseToss sx
| otherwise = parseToss sx
notToss :: Co... |
Keep all operations the same but rewrite the snippet in Haskell. | #include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <math.h>
long long x, y, dx, dy, scale, clen, cscale;
typedef struct { double r, g, b; } rgb;
rgb ** pix;
void sc_up()
{
scale *= 2; x *= 2; y *= 2;
cscale *= 3;
}
void h_rgb(long long x, long long y)
{
rgb *p = &pix[y][x];
# define SAT 1
d... | import Diagrams.Prelude
import Diagrams.Backend.Cairo.CmdLine
triangle = eqTriangle # fc black # lw 0
reduce t = t
===
(t ||| t)
sierpinski = iterate reduce triangle
main = defaultMain $ sierpinski !! 7
|
Produce a language-to-language conversion: from C to Haskell, same semantics. | #include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <math.h>
long long x, y, dx, dy, scale, clen, cscale;
typedef struct { double r, g, b; } rgb;
rgb ** pix;
void sc_up()
{
scale *= 2; x *= 2; y *= 2;
cscale *= 3;
}
void h_rgb(long long x, long long y)
{
rgb *p = &pix[y][x];
# define SAT 1
d... | import Diagrams.Prelude
import Diagrams.Backend.Cairo.CmdLine
triangle = eqTriangle # fc black # lw 0
reduce t = t
===
(t ||| t)
sierpinski = iterate reduce triangle
main = defaultMain $ sierpinski !! 7
|
Generate an equivalent Haskell version of this C code. | #include "stdio.h"
#include "stdbool.h"
#define ARRAY_LEN(a,T) (sizeof(a) / sizeof(T))
struct Interval {
int start, end;
bool print;
};
int main() {
struct Interval intervals[] = {
{2, 1000, true},
{1000, 4000, true},
{2, 10000, false},
{2, 100000, false},
{2, 1000... |
import Data.List (intercalate)
import Text.Printf (printf)
import Data.List.Split (chunksOf)
isEban :: Int -> Bool
isEban n = all (`elem` [0, 2, 4, 6]) z
where
(b, r1) = n `quotRem` (10 ^ 9)
(m, r2) = r1 `quotRem` (10 ^ 6)
(t, r3) = r2 `quotRem` (10 ^ 3)
z = b : map (\x -> if x >= 30 && x <= 66 then x... |
Generate an equivalent Haskell version of this C code. | #include "stdio.h"
#include "stdbool.h"
#define ARRAY_LEN(a,T) (sizeof(a) / sizeof(T))
struct Interval {
int start, end;
bool print;
};
int main() {
struct Interval intervals[] = {
{2, 1000, true},
{1000, 4000, true},
{2, 10000, false},
{2, 100000, false},
{2, 1000... |
import Data.List (intercalate)
import Text.Printf (printf)
import Data.List.Split (chunksOf)
isEban :: Int -> Bool
isEban n = all (`elem` [0, 2, 4, 6]) z
where
(b, r1) = n `quotRem` (10 ^ 9)
(m, r2) = r1 `quotRem` (10 ^ 6)
(t, r3) = r2 `quotRem` (10 ^ 3)
z = b : map (\x -> if x >= 30 && x <= 66 then x... |
Write the same code in Haskell as shown below in C. | #include <stdio.h>
#include <string.h>
#include <stdint.h>
#include <stdlib.h>
#define MAX(x,y) ((x) > (y) ? (x) : (y))
#define MIN(x,y) ((x) < (y) ? (x) : (y))
size_t base20(unsigned int n, uint8_t *out) {
uint8_t *start = out;
do {*out++ = n % 20;} while (n /= 20);
size_t length = out - start;
... | import Data.Bool (bool)
import Data.List (intercalate, transpose)
import qualified Data.Map.Strict as M
import Data.Maybe (maybe)
main :: IO ()
main =
(putStrLn . unlines) $
mayanFramed
<$> [ 4005,
8017,
326205,
886205,
1081439556,
1000000,
... |
Convert this C snippet to Haskell and keep its semantics consistent. | #include <stdio.h>
int valid(int n, int nuts)
{
int k;
for (k = n; k; k--, nuts -= 1 + nuts/n)
if (nuts%n != 1) return 0;
return nuts && !(nuts%n);
}
int main(void)
{
int n, x;
for (n = 2; n < 10; n++) {
for (x = 0; !valid(n, x); x++);
printf("%d: %d\n", n, x);
}
return 0;
}
| import Control.Monad ((>=>))
import Data.Maybe (mapMaybe)
import System.Environment (getArgs)
tryFor :: Int -> Int -> Maybe Int
tryFor s = foldr (>=>) pure $ replicate s step
where
step n
| n `mod` (s - 1) == 0 = Just $ n * s `div` (s - 1) + 1
| otherwise = Nothing
main :: IO ()
main = do
arg... |
Change the programming language of this snippet from C to Haskell without modifying what it does. | #include <stdio.h>
int valid(int n, int nuts)
{
int k;
for (k = n; k; k--, nuts -= 1 + nuts/n)
if (nuts%n != 1) return 0;
return nuts && !(nuts%n);
}
int main(void)
{
int n, x;
for (n = 2; n < 10; n++) {
for (x = 0; !valid(n, x); x++);
printf("%d: %d\n", n, x);
}
return 0;
}
| import Control.Monad ((>=>))
import Data.Maybe (mapMaybe)
import System.Environment (getArgs)
tryFor :: Int -> Int -> Maybe Int
tryFor s = foldr (>=>) pure $ replicate s step
where
step n
| n `mod` (s - 1) == 0 = Just $ n * s `div` (s - 1) + 1
| otherwise = Nothing
main :: IO ()
main = do
arg... |
Produce a language-to-language conversion: from C to Haskell, same semantics. | #include<unistd.h>
#include<stdio.h>
#include<time.h>
#define SHORTLAG 1000
#define LONGLAG 2000
int main(){
int i,times,hour,min,sec,min1,min2;
time_t t;
struct tm* currentTime;
while(1){
time(&t);
currentTime = localtime(&t);
hour = currentTime->tm_hour;
min = currentTime->tm_min;
sec = curren... | import Control.Concurrent
import Control.Monad
import Data.Time
import Text.Printf
type Microsecond = Int
type Scheduler = TimeOfDay -> Microsecond
getTime :: TimeZone -> IO TimeOfDay
getTime tz = do
t <- getCurrentTime
return $ localTimeOfDay $ utcToLocalTime tz t
getGMTTime = getTime utc
getLocalTime... |
Keep all operations the same but rewrite the snippet in Haskell. | #include<unistd.h>
#include<stdio.h>
#include<time.h>
#define SHORTLAG 1000
#define LONGLAG 2000
int main(){
int i,times,hour,min,sec,min1,min2;
time_t t;
struct tm* currentTime;
while(1){
time(&t);
currentTime = localtime(&t);
hour = currentTime->tm_hour;
min = currentTime->tm_min;
sec = curren... | import Control.Concurrent
import Control.Monad
import Data.Time
import Text.Printf
type Microsecond = Int
type Scheduler = TimeOfDay -> Microsecond
getTime :: TimeZone -> IO TimeOfDay
getTime tz = do
t <- getCurrentTime
return $ localTimeOfDay $ utcToLocalTime tz t
getGMTTime = getTime utc
getLocalTime... |
Rewrite this program in Haskell while keeping its functionality equivalent to the C version. | #include<graphics.h>
#include<math.h>
#define factor M_PI/180
#define LAG 1000
void polySpiral(int windowWidth,int windowHeight){
int incr = 0, angle, i, length;
double x,y,x1,y1;
while(1){
incr = (incr + 5)%360;
x = windowWidth/2;
y = windowHeight/2;
length = 5;
angle = incr;
for(i=1;i<=15... |
import Reflex
import Reflex.Dom
import Reflex.Dom.Time
import Data.Text (Text, pack)
import Data.Map (Map, fromList)
import Data.Time.Clock (getCurrentTime)
import Control.Monad.Trans (liftIO)
type Point = (Float,Float)
type Segment = (Point,Point)
main = mainWidget $ do
dTick <- tickLossy 0.05 =<< liftIO ge... |
Transform the following C implementation into Haskell, maintaining the same output and logic. | #include<graphics.h>
#include<math.h>
#define factor M_PI/180
#define LAG 1000
void polySpiral(int windowWidth,int windowHeight){
int incr = 0, angle, i, length;
double x,y,x1,y1;
while(1){
incr = (incr + 5)%360;
x = windowWidth/2;
y = windowHeight/2;
length = 5;
angle = incr;
for(i=1;i<=15... |
import Reflex
import Reflex.Dom
import Reflex.Dom.Time
import Data.Text (Text, pack)
import Data.Map (Map, fromList)
import Data.Time.Clock (getCurrentTime)
import Control.Monad.Trans (liftIO)
type Point = (Float,Float)
type Segment = (Point,Point)
main = mainWidget $ do
dTick <- tickLossy 0.05 =<< liftIO ge... |
Convert this C snippet to Haskell and keep its semantics consistent. |
#include <ctime>
#include <cstdint>
extern "C" {
int64_t from date(const char* string) {
struct tm tmInfo = {0};
strptime(string, "%Y-%m-%d", &tmInfo);
return mktime(&tmInfo);
}
}
| import Data.List
import Data.Maybe
import System.IO (readFile)
import Text.Read (readMaybe)
import Control.Applicative ((<|>))
newtype DB = DB { entries :: [Patient] }
deriving Show
instance Semigroup DB where
DB a <> DB b = normalize $ a <> b
instance Monoid DB where
mempty = DB []
normalize :: [Patient] -... |
Write a version of this C function in Haskell with identical behavior. | #include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define N_SITES 150
double site[N_SITES][2];
unsigned char rgb[N_SITES][3];
int size_x = 640, size_y = 480;
inline double sq2(double x, double y)
{
return x * x + y * y;
}
#define for_k for (k = 0; k < N_SITES; k++)
int nearest_site(double x, double y)
{
... |
module Main where
import System.Random
import Data.Word
import Data.Array.Repa as Repa
import Data.Array.Repa.IO.BMP
sqDistance :: Word32 -> Word32 -> Word32 -> Word32 -> Word32
sqDistance !x1 !y1 !x2 !y2 = ((x1-x2)^2) + ((y1-y2)^2)
centers :: Int -> Int -> Array U DIM2 Word32
centers nCenters nCells =
f... |
Preserve the algorithm and functionality while converting the code from C to Haskell. | #include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define N_SITES 150
double site[N_SITES][2];
unsigned char rgb[N_SITES][3];
int size_x = 640, size_y = 480;
inline double sq2(double x, double y)
{
return x * x + y * y;
}
#define for_k for (k = 0; k < N_SITES; k++)
int nearest_site(double x, double y)
{
... |
module Main where
import System.Random
import Data.Word
import Data.Array.Repa as Repa
import Data.Array.Repa.IO.BMP
sqDistance :: Word32 -> Word32 -> Word32 -> Word32 -> Word32
sqDistance !x1 !y1 !x2 !y2 = ((x1-x2)^2) + ((y1-y2)^2)
centers :: Int -> Int -> Array U DIM2 Word32
centers nCenters nCells =
f... |
Preserve the algorithm and functionality while converting the code from C to Haskell. | #include <ldap.h>
...
char *name, *password;
...
LDAP *ld = ldap_init("ldap.somewhere.com", 389);
ldap_simple_bind_s(ld, name, password);
... after done with it...
ldap_unbind(ld);
|
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... |
Port the following code from C to Haskell with equivalent syntax and logic. | #include <stdio.h>
#include <stdlib.h>
typedef struct {
char *name;
int weight;
int value;
int count;
} item_t;
item_t items[] = {
{"map", 9, 150, 1},
{"compass", 13, 35, 1},
{"water", 153, 200, 2},
{"sandwich", ... | inv = [("map",9,150,1), ("compass",13,35,1), ("water",153,200,2), ("sandwich",50,60,2),
("glucose",15,60,2), ("tin",68,45,3), ("banana",27,60,3), ("apple",39,40,3),
("cheese",23,30,1), ("beer",52,10,3), ("cream",11,70,1), ("camera",32,30,1),
("tshirt",24,15,2), ("trousers",48,10,2), ("umbrella",73,40,1), ("wtrous... |
Write the same code in Haskell as shown below in C. | #include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
int *board, *flood, *known, top = 0, w, h;
static inline int idx(int y, int x) { return y * w + x; }
int neighbors(int c, int *p)
{
int i, j, n = 0;
int y = c / w, x = c % w;
for (i = y - 1; i <= y + 1; i++) {
if (i < 0 || i >= h) c... |
import qualified Data.IntMap as I
import Data.IntMap (IntMap)
import Data.List
import Data.Maybe
import Data.Time.Clock
data BoardProblem = Board
{ cells :: IntMap (IntMap Int)
, endVal :: Int
, onePos :: (Int, Int)
, givens :: [Int]
} deriving (Show, Eq)
tupIns x y v m = I.insert x (I.insert y v (I.find... |
Convert the following code from C to Haskell, ensuring the logic remains intact. | #include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
int *board, *flood, *known, top = 0, w, h;
static inline int idx(int y, int x) { return y * w + x; }
int neighbors(int c, int *p)
{
int i, j, n = 0;
int y = c / w, x = c % w;
for (i = y - 1; i <= y + 1; i++) {
if (i < 0 || i >= h) c... |
import qualified Data.IntMap as I
import Data.IntMap (IntMap)
import Data.List
import Data.Maybe
import Data.Time.Clock
data BoardProblem = Board
{ cells :: IntMap (IntMap Int)
, endVal :: Int
, onePos :: (Int, Int)
, givens :: [Int]
} deriving (Show, Eq)
tupIns x y v m = I.insert x (I.insert y v (I.find... |
Write a version of this C function in Haskell with identical behavior. | #include <stdio.h>
typedef struct node_t *node, node_t;
struct node_t { int v; node next; };
typedef struct { node head, tail; } slist;
void push(slist *l, node e) {
if (!l->head) l->head = e;
if (l->tail) l->tail->next = e;
l->tail = e;
}
node removehead(slist *l) {
node e = l->head;
if (e) {
l->head = e->n... |
merge :: (Ord a) => [a] -> [a] -> [a]
merge [] ys = ys
merge xs [] = xs
merge (x : xs) (y : ys)
| x <= y = x : merge xs (y : ys)
| otherwise = y : merge (x : xs) ys
strandSort :: (Ord a) => [a] -> [a]
strandSort [] = []
strandSort (x : xs) = merge strand (strandSort rest) where
(strand, rest) = extractStrand x xs
... |
Convert this C block to Haskell, preserving its control flow and logic. | #define PI 3.141592653589793
#define TWO_PI 6.283185307179586
double normalize2deg(double a) {
while (a < 0) a += 360;
while (a >= 360) a -= 360;
return a;
}
double normalize2grad(double a) {
while (a < 0) a += 400;
while (a >= 400) a -= 400;
return a;
}
double normalize2mil(double a) {
while (a < 0) a +... |
import Text.Printf
class (Num a, Fractional a, RealFrac a) => Angle a where
fullTurn :: a
mkAngle :: Double -> a
value :: a -> Double
fromTurn :: Double -> a
toTurn :: a -> Double
normalize :: a -> a
fromTurn t = angle t * fullTurn
toTurn a = value $ a / fullTurn
normalize a = a `modu... |
Transform the following C implementation into Haskell, maintaining the same output and logic. | #include <libxml/parser.h>
#include <libxml/xpath.h>
xmlDocPtr getdoc (char *docname) {
xmlDocPtr doc;
doc = xmlParseFile(docname);
return doc;
}
xmlXPathObjectPtr getnodeset (xmlDocPtr doc, xmlChar *xpath){
xmlXPathContextPtr context;
xmlXPathObjectPtr result;
context = xmlXPathNewContext(doc);
result = ... | import Data.List
import Control.Arrow
import Control.Monad
takeWhileIncl :: (a -> Bool) -> [a] -> [a]
takeWhileIncl _ [] = []
takeWhileIncl p (x:xs)
| p x = x : takeWhileIncl p xs
| otherwise = [x]
getmultiLineItem n = takeWhileIncl(not.isInfixOf ("</" ++ n)). dropWhil... |
Port the following code from C to Haskell with equivalent syntax and logic. | #include <stdio.h>
#include <stdlib.h>
#include "curl/curl.h"
int
main(void)
{
CURL *curl;
char buffer[CURL_ERROR_SIZE];
if ((curl = curl_easy_init()) != NULL) {
curl_easy_setopt(curl, CURLOPT_URL, "https:
curl_easy_setopt(curl, CURLOPT_FOLLOWLOCATION, 1);
... |
module Main (main) where
import Data.Aeson (Value)
import Data.Default.Class (def)
import Network.HTTP.Req
( (/:)
, GET(..)
, NoReqBody(..)
, basicAuth
, https
, jsonR... |
Produce a language-to-language conversion: from C to Haskell, same semantics. | #include<stdlib.h>
#include<stdio.h>
typedef struct{
int score;
char name[100];
}entry;
void ordinalRanking(entry* list,int len){
int i;
printf("\n\nOrdinal Ranking\n---------------");
for(i=0;i<len;i++)
printf("\n%d\t%d\t%s",i+1,list[i].score,list[i].name);
}
void standardRanking(entry* list,int len){
... | import Data.List (groupBy, sortBy, intercalate)
type Item = (Int, String)
type ItemList = [Item]
type ItemGroups = [ItemList]
type RankItem a = (a, Int, String)
type RankItemList a = [RankItem a]
prepare :: ItemList -> ItemGroups
prepare = groupBy gf . sortBy (flip compare)
where
gf (a, _) (b, _) = a == b
... |
Translate the given C code snippet into Haskell without altering its behavior. | #include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define strcomp(X, Y) strcasecmp(X, Y)
struct option
{ const char *name, *value;
int flag; };
struct option updlist[] =
{ { "NEEDSPEELING", NULL },
{ "SEEDSREMOVED", "" },
{ "NUMBEROFBANANAS", "1024" },
{ "NUMBEROFSTRAWBERRIES", "62000" },
{ NULL... | import Data.Char (toUpper)
import qualified System.IO.Strict as S
|
Preserve the algorithm and functionality while converting the code from C to Haskell. | #include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <stdbool.h>
#include <ctype.h>
#include <glib.h>
#define ROWS 4
#define COLS 10
#define NPRX "/"
const char *table[ROWS][COLS] =
{
{ "0", "1", "2", "3", "4", "5", "6", "7", "8", "9" },
{ "H", "O", "L", NULL, "M", "E", "S", NULL, "R", ... | import Data.Char
import Data.Map
charToInt :: Char -> Int
charToInt c = ord c - ord '0'
decodeChar :: String -> (Char,String)
decodeChar ('7':'9':r:rs) = (r,rs)
decodeChar ('7':r:rs) = ("PQUVWXYZ. " !! charToInt r, rs)
decodeChar ('3':r:rs) = ("ABCDFGIJKN" !! charToInt r, rs)
decodeChar (r:rs) = ("H... |
Produce a functionally identical Haskell code for the snippet given in C. | %{
int cie, cei, ie, ei;
%}
%%
cie ++cie, ++ie;
cei ++cei, ++ei;
ie ++ie;
ei ++ei;
.|\n ;
%%
int main() {
cie = cei = ie = ei = 0;
yylex();
printf("%s: %s\n","I before E when not preceded by C", (2*ei < ie ? "plausible" : "implausible"));
printf("%s: %s\n","E before I when preceded by C", (2*cie <... | import Network.HTTP
import Text.Regex.TDFA
import Text.Printf
getWordList :: IO String
getWordList = do
response <- simpleHTTP.getRequest$ url
getResponseBody response
where url = "http://wiki.puzzlers.org/pub/wordlists/unixdict.txt"
main = do
words <- getWordList
putStrLn "Checking Rule 1... |
Produce a functionally identical Haskell code for the snippet given in C. | %{
int cie, cei, ie, ei;
%}
%%
cie ++cie, ++ie;
cei ++cei, ++ei;
ie ++ie;
ei ++ei;
.|\n ;
%%
int main() {
cie = cei = ie = ei = 0;
yylex();
printf("%s: %s\n","I before E when not preceded by C", (2*ei < ie ? "plausible" : "implausible"));
printf("%s: %s\n","E before I when preceded by C", (2*cie <... | import Network.HTTP
import Text.Regex.TDFA
import Text.Printf
getWordList :: IO String
getWordList = do
response <- simpleHTTP.getRequest$ url
getResponseBody response
where url = "http://wiki.puzzlers.org/pub/wordlists/unixdict.txt"
main = do
words <- getWordList
putStrLn "Checking Rule 1... |
Write the same code in Haskell as shown below in C. | #include<stdlib.h>
#include<string.h>
#include<stdio.h>
int main(int argc, char** argv)
{
int i,j,sandPileEdge, centerPileHeight, processAgain = 1,top,down,left,right;
int** sandPile;
char* fileName;
static unsigned char colour[3];
if(argc!=3){
printf("Usage: %s <Sand pile side> <Center pile height>",argv[0])... |
module Rosetta.AbelianSandpileModel.ST
( simulate
, test
, toPGM
) where
import Control.Monad.Reader (asks, MonadReader (..), ReaderT, runReaderT)
import Control.Monad.ST (runST, ST)
import Control.Monad.State (evalStateT, forM_, lift, MonadState (..), StateT, modify, when)
import Data.Array.ST (f... |
Produce a functionally identical Haskell code for the snippet given in C. | #include<stdlib.h>
#include<string.h>
#include<stdio.h>
int main(int argc, char** argv)
{
int i,j,sandPileEdge, centerPileHeight, processAgain = 1,top,down,left,right;
int** sandPile;
char* fileName;
static unsigned char colour[3];
if(argc!=3){
printf("Usage: %s <Sand pile side> <Center pile height>",argv[0])... |
module Rosetta.AbelianSandpileModel.ST
( simulate
, test
, toPGM
) where
import Control.Monad.Reader (asks, MonadReader (..), ReaderT, runReaderT)
import Control.Monad.ST (runST, ST)
import Control.Monad.State (evalStateT, forM_, lift, MonadState (..), StateT, modify, when)
import Data.Array.ST (f... |
Convert this C snippet to Haskell and keep its semantics consistent. | void draw_line_antialias(
image img,
unsigned int x0, unsigned int y0,
unsigned int x1, unsigned int y1,
color_component r,
color_component g,
color_component b );
|
module Main (main) where
import Codec.Picture (writePng)
import Codec.Picture.Types (Image, MutableImage(..), Pixel, PixelRGB8(..), createMutableImage, unsafeFreezeImage, writePixel)
import Control.Monad (void)
import Control.Monad.Primitive (PrimMonad, PrimState)
import Data.Foldable (foldlM)
type MImage m px = Mu... |
Produce a functionally identical Haskell code for the snippet given in C. | #include <stdbool.h>
#include <stdio.h>
#include <stdint.h>
#include <stdlib.h>
#include <string.h>
void swap(char* str, int i, int j) {
char c = str[i];
str[i] = str[j];
str[j] = c;
}
void reverse(char* str, int i, int j) {
for (; i < j; ++i, --j)
swap(str, i, j);
}
bool next_permutation(cha... | import Data.List (nub, permutations, sort)
digitShuffleSuccessors :: Integer -> [Integer]
digitShuffleSuccessors n =
(fmap . (+) <*> (nub . sort . concatMap go . permutations . show)) n
where
go ds
| 0 >= delta = []
| otherwise = [delta]
where
delta = (read ds :: Integer) - n
main :... |
Please provide an equivalent version of this C code in Haskell. | #include <stdbool.h>
#include <stdio.h>
#include <stdint.h>
#include <stdlib.h>
#include <string.h>
void swap(char* str, int i, int j) {
char c = str[i];
str[i] = str[j];
str[j] = c;
}
void reverse(char* str, int i, int j) {
for (; i < j; ++i, --j)
swap(str, i, j);
}
bool next_permutation(cha... | import Data.List (nub, permutations, sort)
digitShuffleSuccessors :: Integer -> [Integer]
digitShuffleSuccessors n =
(fmap . (+) <*> (nub . sort . concatMap go . permutations . show)) n
where
go ds
| 0 >= delta = []
| otherwise = [delta]
where
delta = (read ds :: Integer) - n
main :... |
Write a version of this C function in Haskell with identical behavior. | #include <stdint.h>
#include <stdio.h>
#include <glib.h>
typedef struct named_number_tag {
const char* name;
uint64_t number;
} named_number;
const named_number named_numbers[] = {
{ "hundred", 100 },
{ "thousand", 1000 },
{ "million", 1000000 },
{ "billion", 1000000000 },
{ "trillion", 10... | module Main where
import Data.List (find)
import Data.Char (toUpper)
firstNums :: [String]
firstNums =
[ "zero", "one", "two", "three", "four", "five", "six", "seven", "eight", "nine", "ten",
"eleven", "twelve", "thirteen", "fourteen", "fifteen", "sixteen", "seventeen", "eighteen", "nineteen"
]
tens :: [Stri... |
Write the same code in Haskell as shown below in C. | #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,seedX,seedY,windowSide = 500,sumX=0,sumY=0;
int i,iter,choice,numSides;
printf("Enter number of sides : ");
scanf("%d",&numSides);
printf("Enter polygon... | import Graphics.Gloss
pentaflake :: Int -> Picture
pentaflake order = iterate transformation pentagon !! order
where
transformation = Scale s s . foldMap copy [0,72..288]
copy a = Rotate a . Translate 0 x
pentagon = Polygon [ (sin a, cos a) | a <- [0,2*pi/5..2*pi] ]
x = 2*cos(pi/5)
s = 1/(1+x)
... |
Rewrite the snippet below in Haskell so it works the same as the original C code. | #include<stdlib.h>
#include<stdio.h>
char** imageMatrix;
char blankPixel,imagePixel;
typedef struct{
int row,col;
}pixel;
int getBlackNeighbours(int row,int col){
int i,j,sum = 0;
for(i=-1;i<=1;i++){
for(j=-1;j<=1;j++){
if(i!=0 || j!=0)
sum+= (imageMatrix[row+i][col+j]==imagePixel);
}
}
return... | import Data.Array
import qualified Data.List as List
data BW = Black | White
deriving (Eq, Show)
type Index = (Int, Int)
type BWArray = Array Index BW
toBW :: Char -> BW
toBW '0' = White
toBW '1' = Black
toBW ' ' = White
toBW '#' = Black
toBW _ = error "toBW: illegal char"
toBWArray :: [String] -> BWArray... |
Port the provided C code into Haskell while preserving the original functionality. | #include<stdlib.h>
#include<locale.h>
#include<wchar.h>
#include<stdio.h>
#include<time.h>
char rank[9];
int pos[8];
void swap(int i,int j){
int temp = pos[i];
pos[i] = pos[j];
pos[j] = temp;
}
void generateFirstRank(){
int kPos,qPos,bPos1,bPos2,rPos1,rPos2,nPos1,nPos2,i;
for(i=0;i<8;i++){
rank[i] = 'e... | import Data.List
import qualified Data.Set as Set
data Piece = K | Q | R | B | N deriving (Eq, Ord, Show)
isChess960 :: [Piece] -> Bool
isChess960 rank =
(odd . sum $ findIndices (== B) rank) && king > rookA && king < rookB
where
Just king = findIndex (== K) rank
[rookA, rookB] = findIndices (== R) r... |
Convert this C snippet to Haskell and keep its semantics consistent. | #include <stdbool.h>
#include <stdio.h>
#include <stdint.h>
#include <glib.h>
typedef uint64_t integer;
typedef struct number_names_tag {
const char* cardinal;
const char* ordinal;
} number_names;
const number_names small[] = {
{ "zero", "zeroth" }, { "one", "first" }, { "two", "second" },
{ "three",... | spellOrdinal :: Integer -> String
spellOrdinal n
| n <= 0 = "not ordinal"
| n < 20 = small n
| n < 100 = case divMod n 10 of
(k, 0) -> spellInteger (10*k) ++ "th"
(k, m) -> spellInteger (10*k) ++ "-" ++ spellOrdinal m
| n < 1000 = case divMod n 100 of
(k, 0) -> spellInteger (100*k) ++ "th"
... |
Maintain the same structure and functionality when rewriting this code in Haskell. | #include <string.h>
#include <memory.h>
static unsigned int _parseDecimal ( const char** pchCursor )
{
unsigned int nVal = 0;
char chNow;
while ( chNow = **pchCursor, chNow >= '0' && chNow <= '9' )
{
nVal *= 10;
nVal += chNow - '0';
++*pchCursor;
}
return nVal... | import Data.List (isInfixOf)
import Numeric (showHex)
import Data.Char (isDigit)
data IPChunk = IPv6Chunk String | IPv4Chunk (String, String) |
IPv6WithPort [IPChunk] String | IPv6NoPort [IPChunk] |
IPv4WithPort IPChunk String | IPv4NoPort IPChunk |
IPInvalid | IPZeroSection | IPUndefinedWithPort String |
... |
Port the provided C code into Haskell while preserving the original functionality. | #include <math.h>
#include <stdbool.h>
#include <stdio.h>
const double eps = 1e-14;
typedef struct point_t {
double x, y;
} point;
point make_point(double x, double y) {
point p = { x, y };
return p;
}
void print_point(point p) {
double x = p.x;
double y = p.y;
if (x == 0) {
x = 0;
... | import Data.Tuple.Curry
main :: IO ()
main =
mapM_ putStrLn $
concatMap
(("" :) . uncurryN task)
[ ((-10, 11), (10, -9), ((3, -5), 3))
, ((-10, 11), (-11, 12), ((3, -5), 3))
, ((3, -2), (7, -2), ((3, -5), 3))
, ((3, -2), (7, -2), ((0, 0), 4))
, ((0, -3), (0, 6), ((0, 0), 4))
, ((6, 3), ... |
Write the same code in Haskell as shown below in C. | #include <stdio.h>
#include <string.h>
int findNumOfDec(const char *s) {
int pos = 0;
while (s[pos] && s[pos++] != '.') {}
return strlen(s + pos);
}
void test(const char *s) {
int num = findNumOfDec(s);
const char *p = num != 1 ? "s" : "";
printf("%s has %d decimal%s\n", s, num, p);
}
int ma... | decimal :: String -> Int
decimal [] = 0
decimal ('.':xs) = length xs
decimal (_:xs) = decimal xs
numDecimal :: Double -> Int
numDecimal = decimal . show
main = print . map numDecimal $ [12.0, 12.345, 12.3450, 12.345555555555, 12.34555555555555555555, 1.2345e+54]
|
Rewrite the snippet below in Haskell so it works the same as the original C code. | #include<stdio.h>
#include<stdlib.h>
#define min(a, b) (a<=b?a:b)
void minab( unsigned int n ) {
int i, j;
for(i=0;i<n;i++) {
for(j=0;j<n;j++) {
printf( "%2d ", min( min(i, n-1-i), min(j, n-1-j) ));
}
printf( "\n" );
}
return;
}
int main(void) {
minab(10);
... | import Data.List.Split (chunksOf)
distancesToEdge :: Int -> [[Int]]
distancesToEdge n =
( \i ->
chunksOf n $
(\(x, y) -> minimum [x, y, i - x, i - y])
<$> (fmap (,) >>= (<*>)) [0 .. i]
)
$ pred n
main :: IO ()
main =
mapM_ putStrLn $
showMatrix . distancesToEdge <$> [10, 9, 2,... |
Produce a functionally identical Haskell code for the snippet given in C. | #include <stdio.h>
#include <math.h>
typedef struct {
double x;
double y;
} pair;
int main() {
double list[17] = {1, 8, 2, -3, 0, 1, 1, -2.3, 0, 5.5, 8,6, 2, 9, 11, 10, 3};
double diff, maxDiff = -1;
pair maxPairs[5];
int i, count = 0;
for (i = 1; i < 17; ++i) {
diff = fabs(list[i-... | import Data.List (maximumBy)
import Data.Ord (comparing)
maxDeltas :: (Num a, Ord a) => [a] -> [(a, (a, a))]
maxDeltas xs = filter ((delta ==) . fst) pairs
where
pairs =
zipWith
(\a b -> (abs (a - b), (a, b)))
xs
(tail xs)
delta = fst $ maximumBy (comparing fst) pairs
main :: I... |
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>
typedef char *string;
typedef struct node_t {
string symbol;
double weight;
struct node_t *next;
} node;
node *make_node(string symbol, double weight) {
node *nptr = malloc(sizeof(node));
if (nptr) {
nptr->symbol = symbol;
... | import Control.Monad (forM_)
import Control.Monad.Reader (Reader, ask, runReader)
import Data.Bifunctor (first)
import Data.Map (Map)
import qualified Data.Map as M
import Data.Void (Void)
import System.Environment (getArgs)
import System.IO (IOMode(ReadMode), withFile)
import System.IO.Strict (hGetContents)
import Tex... |
Change the following C code into Haskell without altering its purpose. | #include<stdio.h>
#include<stdlib.h>
int isprime( int p ) {
int i;
if(p==2) return 1;
if(!(p%2)) return 0;
for(i=3; i*i<=p; i+=2) {
if(!(p%i)) return 0;
}
return 1;
}
int nextprime( int p ) {
int i=0;
if(p==0) return 2;
if(p<3) return p+1;
while(!isprime(++i + p));
r... | import Data.List.Split ( divvy )
isSquare :: Int -> Bool
isSquare n = (snd $ properFraction $ sqrt $ fromIntegral n) == 0.0
isPrime :: Int -> Bool
isPrime n
|n == 2 = True
|n == 1 = False
|otherwise = null $ filter (\i -> mod n i == 0 ) [2 .. root]
where
root :: Int
root = floor $ sqrt $ from... |
Can you help me rewrite this code in Haskell instead of C, keeping it the same logically? | #include<stdio.h>
#include<stdlib.h>
int isprime( int p ) {
int i;
if(p==2) return 1;
if(!(p%2)) return 0;
for(i=3; i*i<=p; i+=2) {
if(!(p%i)) return 0;
}
return 1;
}
int nextprime( int p ) {
int i=0;
if(p==0) return 2;
if(p<3) return p+1;
while(!isprime(++i + p));
r... | import Data.List.Split ( divvy )
isSquare :: Int -> Bool
isSquare n = (snd $ properFraction $ sqrt $ fromIntegral n) == 0.0
isPrime :: Int -> Bool
isPrime n
|n == 2 = True
|n == 1 = False
|otherwise = null $ filter (\i -> mod n i == 0 ) [2 .. root]
where
root :: Int
root = floor $ sqrt $ from... |
Produce a language-to-language conversion: from C to Haskell, same semantics. | #include <stdio.h>
#include <stdlib.h>
#include <string.h>
void farey(int n)
{
typedef struct { int d, n; } frac;
frac f1 = {0, 1}, f2 = {1, n}, t;
int k;
printf("%d/%d %d/%d", 0, 1, 1, n);
while (f2.n > 1) {
k = (n + f1.n) / f2.n;
t = f1, f1 = f2, f2 = (frac) { f2.d * k - t.d, f2.n * k - t.n };
printf(" %... | import Data.List (unfoldr, mapAccumR)
import Data.Ratio ((%), denominator, numerator)
import Text.Printf (PrintfArg, printf)
farey :: Integer -> [Rational]
farey n = 0 : unfoldr step (0, 1, 1, n)
where
step (a, b, c, d)
| c > n = Nothing
| otherwise =
let k = (n + b) `quot` d
in Just... |
Write the same code in Haskell as shown below in C. | #include <stdio.h>
#include <stdlib.h>
#include <string.h>
void farey(int n)
{
typedef struct { int d, n; } frac;
frac f1 = {0, 1}, f2 = {1, n}, t;
int k;
printf("%d/%d %d/%d", 0, 1, 1, n);
while (f2.n > 1) {
k = (n + f1.n) / f2.n;
t = f1, f1 = f2, f2 = (frac) { f2.d * k - t.d, f2.n * k - t.n };
printf(" %... | import Data.List (unfoldr, mapAccumR)
import Data.Ratio ((%), denominator, numerator)
import Text.Printf (PrintfArg, printf)
farey :: Integer -> [Rational]
farey n = 0 : unfoldr step (0, 1, 1, n)
where
step (a, b, c, d)
| c > n = Nothing
| otherwise =
let k = (n + b) `quot` d
in Just... |
Produce a language-to-language conversion: from C to Haskell, same semantics. | #include<stdlib.h>
#include<string.h>
#include<stdio.h>
unsigned long long bruteForceProperDivisorSum(unsigned long long n){
unsigned long long i,sum = 0;
for(i=1;i<(n+1)/2;i++)
if(n%i==0 && n!=i)
sum += i;
return sum;
}
void printSeries(unsigned long long* arr,int size,char* type){
int i;
printf("\n... | divisors :: (Integral a) => a -> [a]
divisors n = filter ((0 ==) . (n `mod`)) [1 .. (n `div` 2)]
data Class
= Terminating
| Perfect
| Amicable
| Sociable
| Aspiring
| Cyclic
| Nonterminating
deriving (Show)
aliquot :: (Integral a) => a -> [a]
aliquot 0 = [0]
aliquot n = n : (aliquot $ sum $ divisors n... |
Convert this C snippet to Haskell and keep its semantics consistent. | #include<stdlib.h>
#include<string.h>
#include<stdio.h>
unsigned long long bruteForceProperDivisorSum(unsigned long long n){
unsigned long long i,sum = 0;
for(i=1;i<(n+1)/2;i++)
if(n%i==0 && n!=i)
sum += i;
return sum;
}
void printSeries(unsigned long long* arr,int size,char* type){
int i;
printf("\n... | divisors :: (Integral a) => a -> [a]
divisors n = filter ((0 ==) . (n `mod`)) [1 .. (n `div` 2)]
data Class
= Terminating
| Perfect
| Amicable
| Sociable
| Aspiring
| Cyclic
| Nonterminating
deriving (Show)
aliquot :: (Integral a) => a -> [a]
aliquot 0 = [0]
aliquot n = n : (aliquot $ sum $ divisors n... |
Produce a functionally identical Haskell code for the snippet given in C. | #include <stdio.h>
#include <string.h>
typedef int bool;
typedef unsigned long long ull;
#define TRUE 1
#define FALSE 0
bool is_prime(ull n) {
ull d;
if (n < 2) return FALSE;
if (!(n % 2)) return n == 2;
if (!(n % 3)) return n == 3;
d = 5;
while (d * d <= n) {
if (!(n % d)) return F... | import Data.List.Split ( chunksOf )
import Data.List ( (!!) )
isPrime :: Int -> Bool
isPrime n
|n == 2 = True
|n == 1 = False
|otherwise = null $ filter (\i -> mod n i == 0 ) [2 .. root]
where
root :: Int
root = floor $ sqrt $ fromIntegral n
isMagnanimous :: Int -> Bool
isMagnanimous n = a... |
Convert this C block to Haskell, preserving its control flow and logic. | #include <stdbool.h>
#include <stdint.h>
#include <stdio.h>
bool isPrime(uint64_t n) {
uint64_t test;
if (n < 2) return false;
if (n % 2 == 0) return n == 2;
if (n % 3 == 0) return n == 3;
test = 5;
while (test * test < n) {
if (n % test == 0) return false;
test += 2;
... | import Data.Numbers.Primes (primes)
import Text.Printf (printf)
lucasLehmer :: Int -> Bool
lucasLehmer p = iterate f 4 !! p-2 == 0
where
f b = (b^2 - 2) `mod` m
m = 2^p - 1
main = mapM_ (printf "M %d\n") $ take 20 mersenne
where
mersenne = filter lucasLehmer primes
|
Please provide an equivalent version of this C code in Haskell. | #include <stdbool.h>
#include <stdint.h>
#include <stdio.h>
bool isPrime(uint64_t n) {
uint64_t test;
if (n < 2) return false;
if (n % 2 == 0) return n == 2;
if (n % 3 == 0) return n == 3;
test = 5;
while (test * test < n) {
if (n % test == 0) return false;
test += 2;
... | import Data.Numbers.Primes (primes)
import Text.Printf (printf)
lucasLehmer :: Int -> Bool
lucasLehmer p = iterate f 4 !! p-2 == 0
where
f b = (b^2 - 2) `mod` m
m = 2^p - 1
main = mapM_ (printf "M %d\n") $ take 20 mersenne
where
mersenne = filter lucasLehmer primes
|
Write a version of this C function in Haskell with identical behavior. | #include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <locale.h>
#define TRUE 1
#define FALSE 0
typedef unsigned char bool;
void sieve(bool *c, int limit) {
int i, p = 3, p2;
c[0] = TRUE;
c[1] = TRUE;
for (;;) {
p2 = p * p;
if (p2 >= limit) {
break;... | import Text.Printf (printf)
import Data.Numbers.Primes (isPrime, primes)
type Pair = (Int, Int)
type Triplet = (Int, Int, Int)
type Quad = (Int, Int, Int, Int)
type Quin = (Int, Int, Int, Int, Int)
type Result = ([Pair], [Triplet], [Quad], [Quin], [Int])
groups :: Int -> Result -> Result
groups n r@(p, t, q,... |
Produce a language-to-language conversion: from C to Haskell, same semantics. | #include <stdio.h>
#define ELEMENTS 10000000U
void make_klarner_rado(unsigned int *dst, unsigned int n) {
unsigned int i, i2 = 0, i3 = 0;
unsigned int m, m2 = 1, m3 = 1;
for (i = 0; i < n; ++i) {
dst[i] = m = m2 < m3 ? m2 : m3;
if (m2 == m) m2 = dst[i2++] << 1 | 1;
if (m3 == m) m3... | import Data.List (intercalate)
import Data.List.Ordered (union)
import Data.List.Split (chunksOf)
import Text.Printf (printf)
klarnerRado :: [Integer]
klarnerRado =
1 :
union
(succ . (2 *) <$> klarnerRado)
(succ . (3 *) <$> klarnerRado)
main :: IO ()
main = do
putStrLn "First one hundred elements... |
Change the following C code into Haskell without altering its purpose. | #include <stdio.h>
#define ELEMENTS 10000000U
void make_klarner_rado(unsigned int *dst, unsigned int n) {
unsigned int i, i2 = 0, i3 = 0;
unsigned int m, m2 = 1, m3 = 1;
for (i = 0; i < n; ++i) {
dst[i] = m = m2 < m3 ? m2 : m3;
if (m2 == m) m2 = dst[i2++] << 1 | 1;
if (m3 == m) m3... | import Data.List (intercalate)
import Data.List.Ordered (union)
import Data.List.Split (chunksOf)
import Text.Printf (printf)
klarnerRado :: [Integer]
klarnerRado =
1 :
union
(succ . (2 *) <$> klarnerRado)
(succ . (3 *) <$> klarnerRado)
main :: IO ()
main = do
putStrLn "First one hundred elements... |
Port the following code from C to Haskell with equivalent syntax and logic. | #include <stdio.h>
#include <stdlib.h>
typedef unsigned long long xint;
typedef unsigned uint;
typedef struct {
uint x, y;
xint value;
} sum_t;
xint *cube;
uint n_cubes;
sum_t *pq;
uint pq_len, pq_cap;
void add_cube(void)
{
uint x = n_cubes++;
cube = realloc(cube, sizeof(xint) * (n_cubes + 1));
cube[n_cubes] ... | import Data.List (groupBy, sortOn, tails, transpose)
import Data.Function (on)
taxis :: Int -> [[(Int, ((Int, Int), (Int, Int)))]]
taxis nCubes =
filter ((> 1) . length) $
groupBy (on (==) fst) $
sortOn fst
[ (fst x + fst y, (x, y))
| (x:t) <- tails $ ((^ 3) >>= (,)) <$> [1 .. nCubes]
, y <- t ]
... |
Produce a language-to-language conversion: from C to Haskell, same semantics. | #include <stdbool.h>
#include <stdint.h>
#include <stdio.h>
#include <stdlib.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, 163, 167, 173, 179, 181, 191, 193, 197, 199, 211... | import Text.Printf (printf)
import Data.Numbers.Primes (primes)
xPrimes :: (Real a, Fractional b) => (b -> b -> Bool) -> [a] -> [a]
xPrimes op ps@(p1:p2:p3:xs)
| realToFrac p2 `op` (realToFrac (p1 + p3) / 2) = p2 : xPrimes op (tail ps)
| otherwise = xPrimes op (tail ps)
main :: IO ()
main = do
printf "First 36... |
Generate an equivalent Haskell version of this C code. | #include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <gmp.h>
void mpz_left_fac_ui(mpz_t rop, unsigned long op)
{
mpz_t t1;
mpz_init_set_ui(t1, 1);
mpz_set_ui(rop, 0);
size_t i;
for (i = 1; i <= op; ++i) {
mpz_add(rop, rop, t1);
mpz_mul_ui(t1, t1, i);
}
mpz_c... | leftFact :: [Integer]
leftFact = scanl (+) 0 fact
fact :: [Integer]
fact = scanl (*) 1 [1 ..]
main :: IO ()
main =
mapM_
putStrLn
[ "0 ~ 10:"
, show $ (leftFact !!) <$> [0 .. 10]
, ""
, "20 ~ 110 by tens:"
, unlines $ show . (leftFact !!) <$> [20,30 .. 110]
, ""
, "length of 1,000 ~ ... |
Write a version of this C function in Haskell with identical behavior. | #include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <gmp.h>
void mpz_left_fac_ui(mpz_t rop, unsigned long op)
{
mpz_t t1;
mpz_init_set_ui(t1, 1);
mpz_set_ui(rop, 0);
size_t i;
for (i = 1; i <= op; ++i) {
mpz_add(rop, rop, t1);
mpz_mul_ui(t1, t1, i);
}
mpz_c... | leftFact :: [Integer]
leftFact = scanl (+) 0 fact
fact :: [Integer]
fact = scanl (*) 1 [1 ..]
main :: IO ()
main =
mapM_
putStrLn
[ "0 ~ 10:"
, show $ (leftFact !!) <$> [0 .. 10]
, ""
, "20 ~ 110 by tens:"
, unlines $ show . (leftFact !!) <$> [20,30 .. 110]
, ""
, "length of 1,000 ~ ... |
Rewrite the snippet below in Haskell so it works the same as the original C code. | #include <locale.h>
#include <stdbool.h>
#include <stdint.h>
#include <stdio.h>
bool is_prime(uint64_t n) {
if (n < 2)
return false;
if (n % 2 == 0)
return n == 2;
if (n % 3 == 0)
return n == 3;
for (uint64_t p = 5; p * p <= n; p += 4) {
if (n % p == 0)
retur... | import Control.Monad.Memo (Memo, memo, startEvalMemo)
import Math.NumberTheory.Primes.Testing (isPrime)
import System.Environment (getArgs)
import Text.Printf (printf)
type I = Integer
motzkin :: I -> Memo I I I
motzkin 0 = return 1
motzkin 1 = return 1
motzkin n = do
m1 <- memo motzkin (n-1)
m2 <- memo motzkin... |
Convert the following code from C to Haskell, ensuring the logic remains intact. | #include <stdio.h>
#define sqr(x) ((x) * (x))
#define greet printf("Hello There!\n")
int twice(int x)
{
return 2 * x;
}
int main(void)
{
int x;
printf("This will demonstrate function and label scopes.\n");
printf("All output is happening through printf(), a function declared in the header stdio.h, which is exte... | add3 :: Int -> Int-> Int-> Int
add3 x y z = add2 x y + z
add2 :: Int -> Int -> Int
add2 x y = x + y
main :: putStrLn(show (add3 5 6 5))
|
Please provide an equivalent version of this C code in Haskell. | #include <stdio.h>
static int p[19] = {0, 0, 1, 1, 0, 1, 0, 1, 0, 0,
0, 1, 0, 1, 0, 0, 0, 1, 0};
int isstrange(long n) {
if (n < 10) return 0;
for (; n >= 10; n /= 10) {
if (!p[n%10 + (n/10)%10]) return 0;
}
return 1;
}
int main(void) {
long n;
int k = 0;
for ... | import Data.List (intercalate)
import Data.List.Split (chunksOf)
isStrangePlus :: Int -> Bool
isStrangePlus n =
all
(\(a, b) -> (a + b) `elem` [2, 3, 5, 7, 11, 13, 17])
$ (zip <*> tail) (digits n)
digits :: Int -> [Int]
digits = fmap (read . return) . show
main =
let xs = filter isStrangePlus [100 ..... |
Translate this program into Haskell but keep the logic exactly as in C. | #include <stdio.h>
static int p[19] = {0, 0, 1, 1, 0, 1, 0, 1, 0, 0,
0, 1, 0, 1, 0, 0, 0, 1, 0};
int isstrange(long n) {
if (n < 10) return 0;
for (; n >= 10; n /= 10) {
if (!p[n%10 + (n/10)%10]) return 0;
}
return 1;
}
int main(void) {
long n;
int k = 0;
for ... | import Data.List (intercalate)
import Data.List.Split (chunksOf)
isStrangePlus :: Int -> Bool
isStrangePlus n =
all
(\(a, b) -> (a + b) `elem` [2, 3, 5, 7, 11, 13, 17])
$ (zip <*> tail) (digits n)
digits :: Int -> [Int]
digits = fmap (read . return) . show
main =
let xs = filter isStrangePlus [100 ..... |
Transform the following C implementation into Haskell, maintaining the same output and logic. | #include <locale.h>
#include <stdbool.h>
#include <stdint.h>
#include <stdio.h>
typedef uint32_t integer;
integer next_prime_digit_number(integer n) {
if (n == 0)
return 2;
switch (n % 10) {
case 2:
return n + 1;
case 3:
case 5:
return n + 2;
default:
return 2 +... |
import Control.Monad (guard)
import Math.NumberTheory.Primes.Testing (isPrime)
import Data.List.Split (chunksOf)
import Data.List (intercalate)
import Text.Printf (printf)
smarandache :: [Integer]
smarandache = [2,3,5,7] <> s [2,3,5,7] >>= \x -> guard (isPrime x) >> [x]
where s xs = r <> s r where r = xs >>= \x -> [... |
Maintain the same structure and functionality when rewriting this code in Haskell. | #include<stdlib.h>
#include<ctype.h>
#include<stdio.h>
int** doublyEvenMagicSquare(int n) {
if (n < 4 || n % 4 != 0)
return NULL;
int bits = 38505;
int size = n * n;
int mult = n / 4,i,r,c,bitPos;
int** result = (int**)malloc(n*sizeof(int*));
for(i=0;i<n;i++)
result[i] = (int*)malloc(n*sizeof(int));
fo... | import Data.List (transpose, unfoldr, intercalate)
import Data.List.Split (chunksOf)
import Data.Bool (bool)
import Control.Monad (forM_)
magicSquare :: Int -> [[Int]]
magicSquare n
| rem n 4 > 0 = []
| otherwise =
chunksOf n $ zipWith (flip (bool =<< (-) limit)) series [1 .. sqr]
where
sqr = n * n
l... |
Generate an equivalent Haskell version of this C code. | #include <stdio.h>
#include <stdlib.h>
#include <math.h>
#define TRUE 1
#define FALSE 0
#define TRILLION 1000000000000
typedef unsigned char bool;
typedef unsigned long long uint64;
void sieve(uint64 limit, uint64 *primes, uint64 *length) {
uint64 i, count, p, p2;
bool *c = calloc(limit + 1, sizeof(bool)); ... | import Data.List.Split (chunksOf)
import Math.NumberTheory.Primes (factorise)
import Text.Printf (printf)
isSquareFree :: Integer -> Bool
isSquareFree = all ((== 1) . snd) . factorise
squareFrees :: Integer -> Integer -> [Integer]
squareFrees lo hi = filter isSquareFree [lo..hi]
counts :: (Ord a, Num b) => [a] ... |
Write a version of this C function in Haskell with identical behavior. | #include <stdio.h>
#include <stdlib.h>
#include <time.h>
typedef unsigned char bool;
#define TRUE 1
#define FALSE 0
#define MILLION 1000000
#define BILLION 1000 * MILLION
#define MAX_COUNT 2*BILLION + 9*9 + 1
void sieve(bool *sv) {
int n = 0, s[8], a, b, c, d, e, f, g, h, i, j;
for (a = 0; a < 2; ++a) {
... | import Control.Monad (forM_)
import Text.Printf
selfs :: [Integer]
selfs = sieve (sumFs [0..]) [0..]
where
sumFs = zipWith (+) [ a+b+c+d+e+f+g+h+i+j
| a <- [0..9] , b <- [0..9]
, c <- [0..9] , d <- [0..9]
, e <- [0..9] , f <- [0..9]
... |
Ensure the translated Haskell code behaves exactly like the original C snippet. | #include <locale.h>
#include <stdbool.h>
#include <stdint.h>
#include <stdio.h>
uint64_t digit_sum(uint64_t n, uint64_t sum) {
++sum;
while (n > 0 && n % 10 == 0) {
sum -= 9;
n /= 10;
}
return sum;
}
inline bool divisible(uint64_t n, uint64_t d) {
if ((d & 1) == 0 && (n & 1) == 1... |
import Control.Monad (guard)
import Text.Printf (printf)
import Data.List (intercalate, unfoldr)
import Data.List.Split (chunksOf)
import Data.Tuple (swap)
nivens :: [Int]
nivens = [1..] >>= \n -> guard (n `rem` digitSum n == 0) >> [n]
where
digitSum = sum . unfoldr (\x -> guard (x > 0) >> pure (swap $ x `quotRem`... |
Can you help me rewrite this code in Haskell instead of C, keeping it the same logically? | #include<string.h>
#include<stdlib.h>
#include<ctype.h>
#include<stdio.h>
#define UNITS_LENGTH 13
int main(int argC,char* argV[])
{
int i,reference;
char *units[UNITS_LENGTH] = {"kilometer","meter","centimeter","tochka","liniya","diuym","vershok","piad","fut","arshin","sazhen","versta","milia"};
double factor, ... | module Main where
import Text.Printf (printf)
import System.Environment (getArgs, getProgName)
tochka = ("tochka" , 0.000254)
liniya = ("liniya" , 0.00254)
centimeter = ("centimeter", 0.01)
diuym = ("diuym" , 0.0254)
vershok = ("vershok" , 0.04445)
piad = ("piad" , 0.1778)
fut ... |
Maintain the same structure and functionality when rewriting this code in Haskell. | #include <stdio.h>
unsigned digit_sum(unsigned n) {
unsigned sum = 0;
do { sum += n % 10; }
while(n /= 10);
return sum;
}
unsigned a131382(unsigned n) {
unsigned m;
for (m = 1; n != digit_sum(m*n); m++);
return m;
}
int main() {
unsigned n;
for (n = 1; n <= 70; n++) {
prin... | import Data.Bifunctor (first)
import Data.List (elemIndex, intercalate, transpose)
import Data.List.Split (chunksOf)
import Data.Maybe (fromJust)
import Text.Printf (printf)
a131382 :: [Int]
a131382 =
fromJust . (elemIndex <*> productDigitSums)
<$> [1 ..]
productDigitSums :: Int -> [Int]
productDigitSums n = ... |
Translate this program into Haskell but keep the logic exactly as in C. | #include <stdio.h>
#include <math.h>
#include <string.h>
#define N 2200
int main(int argc, char **argv){
int a,b,c,d;
int r[N+1];
memset(r,0,sizeof(r));
for(a=1; a<=N; a++){
for(b=a; b<=N; b++){
int aabb;
if(a&1 && b&1) continue;
aabb=a*a + b*b;
for(c=b; c<=N; c++){
int aabbcc=aabb +... | powersOfTwo :: [Int]
powersOfTwo = iterate (2 *) 1
unrepresentable :: [Int]
unrepresentable = merge powersOfTwo ((5 *) <$> powersOfTwo)
merge :: [Int] -> [Int] -> [Int]
merge xxs@(x:xs) yys@(y:ys)
| x < y = x : merge xs yys
| otherwise = y : merge xxs ys
main :: IO ()
main = do
putStrLn "The values of d <= 220... |
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 node_t {
int x, y;
struct node_t *prev, *next;
} node;
node *new_node(int x, int y) {
node *n = malloc(sizeof(node));
n->x = x;
n->y = y;
n->next = NULL;
n->prev = NULL;
return n;
}
void free_node(node **n) {
... | import Data.List (intersect)
s1, s2, s3, s4 :: [(Int, Int)]
s1 = [(x, y) | x <- [1 .. 100], y <- [1 .. 100], 1 < x && x < y && x + y < 100]
add, mul :: (Int, Int) -> Int
add (x, y) = x + y
mul (x, y) = x * y
sumEq, mulEq :: (Int, Int) -> [(Int, Int)]
sumEq p = filter (\q -> add q == add p) s1
mulEq p = filter (\q ->... |
Produce a functionally identical Haskell code for the snippet given in C. | #include <stdio.h>
#include <complex.h>
#include <math.h>
#define FMTSPEC(arg) _Generic((arg), \
float: "%f", double: "%f", \
long double: "%Lf", unsigned int: "%u", \
unsigned long: "%lu", unsigned long long: "%llu", \
int: "%d", long: "%ld", long long: "%lld", \
default: "(invalid type (%p)")
#... | import Data.Decimal
import Data.Ratio
import Data.Complex
|
Translate this program into Haskell but keep the logic exactly as in C. | #include <stdio.h>
#include <stdlib.h>
#include <math.h>
#define TRUE 1
#define FALSE 0
typedef int bool;
void primeSieve(int *c, int limit, bool processEven, bool primesOnly) {
int i, ix, p, p2;
limit++;
c[0] = TRUE;
c[1] = TRUE;
if (processEven) {
for (i = 4; i < limit; i +=2) c[i] = TR... | import Data.Numbers.Primes
primeSumsOfConsecutiveNumbers :: Integral a => [(a, (a, a))]
primeSumsOfConsecutiveNumbers =
let go a b = [(n, (a, b)) | let n = a + b, isPrime n]
in concat $ zipWith go [1 ..] [2 ..]
main :: IO ()
main = mapM_ print $ take 20 primeSumsOfConsecutiveNumbers
|
Convert the following code from C to Haskell, ensuring the logic remains intact. | #include<stdlib.h>
#include<string.h>
#include<unistd.h>
#include<stdio.h>
int main(int argC,char* argV[])
{
char str[100];
const char d[2] = " ";
char* token;
int i = 0,times,lag;
long int sum = 0, idle, lastSum = 0,lastIdle = 0;
long double idleFraction;
if(argC!=3)
printf("Usage : %s <number of times /pr... | import Data.List ( (!!) )
splitString :: Char -> String -> [String]
splitString c [] = []
splitString c s = let ( item , rest ) = break ( == c ) s
( _ , next ) = break ( /= c ) rest
in item : splitString c next
computeUsage :: String -> Double
computeUsage s = (1.0 - ((lineElements ... |
Convert this C block to Haskell, preserving its control flow and logic. | #include <stdio.h>
#include <stdlib.h>
#include <string.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;
}
void* xrealloc(void* p, size_... | import Data.List
ulam
:: Integral i =>
Int -> i
ulam 1 = 1
ulam 2 = 2
ulam n
| n > 2 = ulams !! (n-1)
ulams
:: Integral n =>
[n]
ulams = 1:2:(nexts [2,1])
nexts us = u: (nexts (u:us))
where
n = length us
[u] = head . filter isSingleton . group . sort $
[v | i <- [0 .. n-2], j ... |
Please provide an equivalent version of this C code in Haskell. | #include <stdio.h>
#include <string.h>
#include <gmp.h>
char *power_of_six(unsigned int n, char *buf) {
mpz_t p;
mpz_init(p);
mpz_ui_pow_ui(p, 6, n);
mpz_get_str(buf, 10, p);
mpz_clear(p);
return buf;
}
char *smallest_six(unsigned int n) {
static char nbuf[32], powbuf[1024];
unsigned i... | import Data.List (find, isInfixOf)
import Text.Printf (printf)
smallest :: Integer -> Integer
smallest n = d
where
Just d = find ((show n `isInfixOf`) . show) sixes
sixes :: [Integer]
sixes = iterate (* 6) 1
main :: IO ()
main =
putStr $
[0 .. 21] >>= printf "%2d: %d\n" <*> smallest
|
Write the same code in Haskell as shown below in C. | #include<stdio.h>
#include<stdlib.h>
int isprime( int p ) {
int i;
if(p==2) return 1;
if(!(p%2)) return 0;
for(i=3; i*i<=p; i+=2) {
if(!(p%i)) return 0;
}
return 1;
}
int main( void ) {
int p;
long int s = 2;
for(p=3;p<2000000;p+=2) {
if(isprime(p)) s+=p;
}
p... | import Data.Numbers.Primes (primes)
sumOfPrimesBelow :: Integral a => a -> a
sumOfPrimesBelow n =
sum $ takeWhile (< n) primes
main :: IO ()
main = print $ sumOfPrimesBelow 2000000
|
Preserve the algorithm and functionality while converting the code from C to Haskell. | #include <stdio.h>
#include <stdbool.h>
bool steady(int n)
{
int mask = 1;
for (int d = n; d != 0; d /= 10)
mask *= 10;
return (n * n) % mask == n;
}
int main()
{
for (int i = 1; i < 10000; i++)
if (steady(i))
printf("%4d^2 = %8d\n", i, i * i);
return 0;
}
| import Control.Monad (join)
import Data.List (isSuffixOf)
p :: Int -> Bool
p = isSuffixOf . show <*> (show . join (*))
main :: IO ()
main =
print $
takeWhile (< 10000) $ filter p [0 ..]
|
Port the provided C code into Haskell while preserving the original functionality. | #include <stdbool.h>
#include <stdio.h>
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, 163, 167, 173, 179, 181, 191, 193, 197, 199,
211, 223, 227, 229, 233, 239, 241, 251, 257, 263,... | import Text.Printf (printf)
import Data.Numbers.Primes (isPrime, primes)
main = do
printf "First 35 safe primes: %s\n" (show $ take 35 safe)
printf "There are %d safe primes below 100,000.\n" (length $ takeWhile (<1000000) safe)
printf "There are %d safe primes below 10,000,000.\n\n" (length $ takeWhile (<10000... |
Convert the following code from C to Haskell, ensuring the logic remains intact. | #include <stdio.h>
#include <gmp.h>
typedef unsigned long ulong;
ulong small_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};
#define MAX_STACK 128
mpz_t tens[MAX_STACK], value[MAX_STACK], answer;
ulong base, seen_depth;
void add_digit(ulong i)
{
ulong d;
for (d = 1; d < b... | primesTo100 = [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]
find2km :: Integral a => a -> (Int,a)
find2km n = f 0 n
where f k m
| r == 1 = (k,m)
| otherwise = f (k+1) q
where (q,r) = quotRem m 2
millerRabinPrimality :: Integer -> Integer -> Bool
miller... |
Port the provided C code into Haskell while preserving the original functionality. | #include <sys/wait.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
void talk(const char *s)
{
pid_t pid;
int status;
pid = fork();
if (pid < 0) {
perror("fork");
exit(1);
}
if (pid == 0) {
execlp("espeak", "espeak", s, (void*)0);
perror("espeak");
_exit(1);
}
waitpid(pid, &status, 0)... | import System.Process (callProcess)
say text = callProcess "espeak" ["
main = say "This is an example of speech synthesis."
|
Write the same code in Haskell as shown below in C. | #ifndef _CSEQUENCE_H
#define _CSEQUENCE_H
#include <stdlib.h>
void setfillconst(double c);
void fillwithconst(double *v, int n);
void fillwithrrange(double *v, int n);
void shuffledrange(double *v, int n);
#endif
| import Data.Time.Clock
import Data.List
type Time = Integer
type Sorter a = [a] -> [a]
timed :: IO a -> IO (a, Time)
timed prog = do
t0 <- getCurrentTime
x <- prog
t1 <- x `seq` getCurrentTime
return (x, ceiling $ 1000000 * diffUTCTime t1 t0)
test :: [a] -> Sorter a -> IO [(Int, Time)]
test set srt = mapM... |
Convert this C snippet to Haskell and keep its semantics consistent. | #include <stdio.h>
typedef struct {int val, op, left, right;} Node;
Node nodes[10000];
int iNodes;
int b;
float eval(Node x){
if (x.op != -1){
float l = eval(nodes[x.left]), r = eval(nodes[x.right]);
switch(x.op){
case 0: return l+r;
case 1: return l-r;
case 2:... | import Data.List
import Data.Ratio
import Control.Monad
import System.Environment (getArgs)
data Expr = Constant Rational |
Expr :+ Expr | Expr :- Expr |
Expr :* Expr | Expr :/ Expr
deriving (Eq)
ops = [(:+), (:-), (:*), (:/)]
instance Show Expr where
show (Constant x) = show $ numerator x
... |
Translate the given C code snippet into Haskell without altering its behavior. | #include <stdio.h>
typedef struct {int val, op, left, right;} Node;
Node nodes[10000];
int iNodes;
int b;
float eval(Node x){
if (x.op != -1){
float l = eval(nodes[x.left]), r = eval(nodes[x.right]);
switch(x.op){
case 0: return l+r;
case 1: return l-r;
case 2:... | import Data.List
import Data.Ratio
import Control.Monad
import System.Environment (getArgs)
data Expr = Constant Rational |
Expr :+ Expr | Expr :- Expr |
Expr :* Expr | Expr :/ Expr
deriving (Eq)
ops = [(:+), (:-), (:*), (:/)]
instance Show Expr where
show (Constant x) = show $ numerator x
... |
Convert this C snippet to Haskell and keep its semantics consistent. | #include "SL_Generated.h"
#include "CImg.h"
using namespace cimg_library;
int main( int argc, char** argv )
{
string fileName = "Pentagon.bmp";
if(argc > 1) fileName = argv[1];
int thetaAxisSize = 640; if(argc > 2) thetaAxisSize = atoi(argv[2]);
int rAxisSize = 480; if(argc > 3) rAxisSize = atoi(argv[... | import Control.Monad (forM_, when)
import Data.Array ((!))
import Data.Array.ST (newArray, writeArray, readArray, runSTArray)
import qualified Data.Foldable as F (maximum)
import System.Environment (getArgs, getProgName)
import Codec.Picture
(DynamicImage(ImageRGB8, ImageRGBA8), Image, PixelRGB8(PixelRGB8),
... |
Rewrite this program in Haskell while keeping its functionality equivalent to the C version. | #include <stdio.h>
#define JOBS 12
#define jobs(a) for (switch_to(a = 0); a < JOBS || !printf("\n"); switch_to(++a))
typedef struct { int seq, cnt; } env_t;
env_t env[JOBS] = {{0, 0}};
int *seq, *cnt;
void hail()
{
printf("% 4d", *seq);
if (*seq == 1) return;
++*cnt;
*seq = (*seq & 1) ? 3 * *seq + 1 : *seq / 2;
... | hailstone n
| n == 1 = 1
| even n = n `div` 2
| odd n = 3*n + 1
|
Convert this C snippet to Haskell and keep its semantics consistent. | #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... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.