Instruction
stringlengths
45
106
input_code
stringlengths
1
13.7k
output_code
stringlengths
1
13.7k
Convert the following code from C to Haskell, ensuring the logic remains intact.
#include <stdio.h> #include <stdlib.h> #include <stdbool.h> #include <locale.h> bool isPrime(int n) { if (n < 2) return false; if (n%2 == 0) return n == 2; if (n%3 == 0) return n == 3; int d = 5; while (d*d <= n) { if (n%d == 0) return false; d += 2; if (n%d == 0) return fal...
import Control.Applicative import Data.List ( sort ) import Data.List.Split ( chunksOf ) 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 solution :: [Int] solut...
Keep all operations the same but rewrite the snippet in Haskell.
#include <stdio.h> #include <gmp.h> void jacobsthal(mpz_t r, unsigned long n) { mpz_t s; mpz_init(s); mpz_set_ui(r, 1); mpz_mul_2exp(r, r, n); mpz_set_ui(s, 1); if (n % 2) mpz_neg(s, s); mpz_sub(r, r, s); mpz_div_ui(r, r, 3); } void jacobsthal_lucas(mpz_t r, unsigned long n) { mpz_...
jacobsthal :: [Integer] jacobsthal = 0 : 1 : zipWith (\x y -> 2 * x + y) jacobsthal (tail jacobsthal) jacobsthalLucas :: [Integer] jacobsthalLucas = 2 : 1 : zipWith (\x y -> 2 * x + y) jacobsthalLucas (tail jacobsthalLucas) jacobsthalOblong :: [Integer] jacobsthalOblong = zipWith (*) jacobsthal (tail jacobsthal) isP...
Port the provided C code into Haskell while preserving the original functionality.
#include <stdio.h> #include <gmp.h> void jacobsthal(mpz_t r, unsigned long n) { mpz_t s; mpz_init(s); mpz_set_ui(r, 1); mpz_mul_2exp(r, r, n); mpz_set_ui(s, 1); if (n % 2) mpz_neg(s, s); mpz_sub(r, r, s); mpz_div_ui(r, r, 3); } void jacobsthal_lucas(mpz_t r, unsigned long n) { mpz_...
jacobsthal :: [Integer] jacobsthal = 0 : 1 : zipWith (\x y -> 2 * x + y) jacobsthal (tail jacobsthal) jacobsthalLucas :: [Integer] jacobsthalLucas = 2 : 1 : zipWith (\x y -> 2 * x + y) jacobsthalLucas (tail jacobsthalLucas) jacobsthalOblong :: [Integer] jacobsthalOblong = zipWith (*) jacobsthal (tail jacobsthal) isP...
Port the following code from C to Haskell with equivalent syntax and logic.
#include <stdbool.h> #include <stdint.h> #include <stdio.h> #define PRIME_COUNT 100000 int64_t PRIMES[PRIME_COUNT]; size_t primeSize = 0; bool isPrime(int n) { size_t i = 0; for (i = 0; i < primeSize; i++) { int64_t p = PRIMES[i]; if (n == p) { return true; } if (n...
import Data.Numbers.Primes (primes) type Result = [(String, [Int])] oneMillionPrimes :: Integral p => [p] oneMillionPrimes = takeWhile (<1_000_000) primes getGroups :: [Int] -> Result getGroups [] = [] getGroups ps@(n:x:y:z:xs) | x-n == 6 && y-x == 4 && z-y == 2 = ("(6 4 2)", [n, x, y, z]) : getGroups...
Port the provided C code into Haskell while preserving the original functionality.
#include <stdio.h> #include <stdint.h> uint8_t prime(uint8_t n) { uint8_t f; if (n < 2) return 0; for (f = 2; f < n; f++) { if (n % f == 0) return 0; } return 1; } uint8_t digit_sum(uint8_t n, uint8_t base) { uint8_t s = 0; do {s += n % base;} while (n /= base); return s; } ...
import Data.Bifunctor (first) import Data.List.Split (chunksOf) import Data.Numbers.Primes (isPrime) digitSumsPrime :: Int -> [Int] -> Bool digitSumsPrime n = all (isPrime . digitSum n) digitSum :: Int -> Int -> Int digitSum n base = go n where go 0 = 0 go n = uncurry (+) (first go $ quotRem n base) mai...
Write the same code in Haskell as shown below in C.
#include <stdbool.h> #include <stdio.h> bool is_prime(int n) { int i = 5; if (n < 2) { return false; } if (n % 2 == 0) { return n == 2; } if (n % 3 == 0) { return n == 3; } while (i * i <= n) { if (n % i == 0) { return false; } ...
import Data.List (scanl) import Data.Numbers.Primes (isPrime, primes) indexedPrimeSums :: [(Integer, Integer, Integer)] indexedPrimeSums = filter (\(_, _, n) -> isPrime n) $ scanl (\(i, _, m) p -> (succ i, p, p + m)) (0, 0, 0) primes main :: IO () main = mapM_ print $ takeWhile (\(_, ...
Convert this C block to Haskell, preserving its control flow and logic.
#include <stdbool.h> #include <stdio.h> bool is_prime(int n) { int i = 5; if (n < 2) { return false; } if (n % 2 == 0) { return n == 2; } if (n % 3 == 0) { return n == 3; } while (i * i <= n) { if (n % i == 0) { return false; } ...
import Data.List (scanl) import Data.Numbers.Primes (isPrime, primes) indexedPrimeSums :: [(Integer, Integer, Integer)] indexedPrimeSums = filter (\(_, _, n) -> isPrime n) $ scanl (\(i, _, m) p -> (succ i, p, p + m)) (0, 0, 0) primes main :: IO () main = mapM_ print $ takeWhile (\(_, ...
Port the provided C code into Haskell while preserving the original functionality.
#include<stdio.h> int main() { int num = 9876432,diff[] = {4,2,2,2},i,j,k=0; char str[10]; start:snprintf(str,10,"%d",num); for(i=0;str[i+1]!=00;i++){ if(str[i]=='0'||str[i]=='5'||num%(str[i]-'0')!=0){ num -= diff[k]; k = (k+1)%4; goto start; } for(j=i+1;str[j]!=00;j++) if(str[i]==str...
import Data.List (maximumBy, permutations, delete) import Data.Ord (comparing) import Data.Bool (bool) unDigits :: [Int] -> Int unDigits = foldl ((+) . (10 *)) 0 ds :: [Int] ds = [1, 2, 3, 4, 6, 7, 8, 9] lcmDigits :: Int lcmDigits = foldr1 lcm ds sevenDigits :: [[Int]] sevenDigits = (`delete` ds) <$> [1, 4, 7] ...
Produce a language-to-language conversion: from C to Haskell, same semantics.
#include<stdio.h> int main() { int num = 9876432,diff[] = {4,2,2,2},i,j,k=0; char str[10]; start:snprintf(str,10,"%d",num); for(i=0;str[i+1]!=00;i++){ if(str[i]=='0'||str[i]=='5'||num%(str[i]-'0')!=0){ num -= diff[k]; k = (k+1)%4; goto start; } for(j=i+1;str[j]!=00;j++) if(str[i]==str...
import Data.List (maximumBy, permutations, delete) import Data.Ord (comparing) import Data.Bool (bool) unDigits :: [Int] -> Int unDigits = foldl ((+) . (10 *)) 0 ds :: [Int] ds = [1, 2, 3, 4, 6, 7, 8, 9] lcmDigits :: Int lcmDigits = foldr1 lcm ds sevenDigits :: [[Int]] sevenDigits = (`delete` ds) <$> [1, 4, 7] ...
Produce a functionally identical Haskell code for the snippet given in C.
#include <stdlib.h> #include <stdio.h> #define SWAP(a, b) (((a) ^= (b)), ((b) ^= (a)), ((a) ^= (b))) int jacobi(unsigned long a, unsigned long n) { if (a >= n) a %= n; int result = 1; while (a) { while ((a & 1) == 0) { a >>= 1; if ((n & 7) == 3 || (n & 7) == 5) result = -result; } SWAP(a, n); if ((a ...
jacobi :: Integer -> Integer -> Integer jacobi 0 1 = 1 jacobi 0 _ = 0 jacobi a n = let a_mod_n = rem a n in if even a_mod_n then case rem n 8 of 1 -> jacobi (div a_mod_n 2) n 3 -> negate $ jacobi (div a_mod_n 2) n 5 -> negate $ jacobi (div a_mod_n 2) n ...
Write a version of this C function in Haskell with identical behavior.
#include <stdlib.h> #include <stdio.h> #define SWAP(a, b) (((a) ^= (b)), ((b) ^= (a)), ((a) ^= (b))) int jacobi(unsigned long a, unsigned long n) { if (a >= n) a %= n; int result = 1; while (a) { while ((a & 1) == 0) { a >>= 1; if ((n & 7) == 3 || (n & 7) == 5) result = -result; } SWAP(a, n); if ((a ...
jacobi :: Integer -> Integer -> Integer jacobi 0 1 = 1 jacobi 0 _ = 0 jacobi a n = let a_mod_n = rem a n in if even a_mod_n then case rem n 8 of 1 -> jacobi (div a_mod_n 2) n 3 -> negate $ jacobi (div a_mod_n 2) n 5 -> negate $ jacobi (div a_mod_n 2) n ...
Translate the given C code snippet into Haskell without altering its behavior.
#include <stdio.h> #include <stdlib.h> #include <string.h> double det_in(double **in, int n, int perm) { if (n == 1) return in[0][0]; double sum = 0, *m[--n]; for (int i = 0; i < n; i++) m[i] = in[i + 1] + 1; for (int i = 0, sgn = 1; i <= n; i++) { sum += sgn * (in[i][0] * det_in(m, n, perm)); if (i == n) ...
sPermutations :: [a] -> [([a], Int)] sPermutations = flip zip (cycle [1, -1]) . foldl aux [[]] where aux items x = do (f, item) <- zip (cycle [reverse, id]) items f (insertEv x item) insertEv x [] = [[x]] insertEv x l@(y:ys) = (x : l) : ((y :) <$>) (insertEv x ys) elemPos :: [[a]] -> Int -> I...
Ensure the translated Haskell code behaves exactly like the original C snippet.
#include <stdio.h> #include <stdlib.h> #include <string.h> double det_in(double **in, int n, int perm) { if (n == 1) return in[0][0]; double sum = 0, *m[--n]; for (int i = 0; i < n; i++) m[i] = in[i + 1] + 1; for (int i = 0, sgn = 1; i <= n; i++) { sum += sgn * (in[i][0] * det_in(m, n, perm)); if (i == n) ...
sPermutations :: [a] -> [([a], Int)] sPermutations = flip zip (cycle [1, -1]) . foldl aux [[]] where aux items x = do (f, item) <- zip (cycle [reverse, id]) items f (insertEv x item) insertEv x [] = [[x]] insertEv x l@(y:ys) = (x : l) : ((y :) <$>) (insertEv x ys) elemPos :: [[a]] -> Int -> I...
Ensure the translated Haskell code behaves exactly like the original C snippet.
#include <stdio.h> #include <string.h> int digitSum(int n) { int s = 0; do {s += n % 10;} while (n /= 10); return s; } int digitSumIsSubstring(int n) { char s_n[32], s_ds[32]; sprintf(s_n, "%d", n); sprintf(s_ds, "%d", digitSum(n)); return strstr(s_n, s_ds) != NULL; } int main() { int...
import Data.Char (digitToInt) import Data.List (isInfixOf) import Data.List.Split (chunksOf) digitSumIsSubString :: String -> Bool digitSumIsSubString = isInfixOf =<< show . foldr ((+) . digitToInt) 0 main :: IO () main = mapM_ putStrLn $ showMatches digitSumIsSubString <$> [999, 10000] showMatches :...
Port the provided C code into Haskell while preserving the original functionality.
#include <stdio.h> #include <string.h> int digitSum(int n) { int s = 0; do {s += n % 10;} while (n /= 10); return s; } int digitSumIsSubstring(int n) { char s_n[32], s_ds[32]; sprintf(s_n, "%d", n); sprintf(s_ds, "%d", digitSum(n)); return strstr(s_n, s_ds) != NULL; } int main() { int...
import Data.Char (digitToInt) import Data.List (isInfixOf) import Data.List.Split (chunksOf) digitSumIsSubString :: String -> Bool digitSumIsSubString = isInfixOf =<< show . foldr ((+) . digitToInt) 0 main :: IO () main = mapM_ putStrLn $ showMatches digitSumIsSubString <$> [999, 10000] showMatches :...
Write the same algorithm in Haskell as shown in this C implementation.
#include<stdlib.h> #include<stdio.h> #include<time.h> void sattoloCycle(void** arr,int count){ int i,j; void* temp; if(count<2) return; for(i=count-1;i>=1;i--){ j = rand()%i; temp = arr[j]; arr[j] = arr[i]; arr[i] = temp; } } int main(int argC,char* argV[]) { int i; if(argC==1) printf("Usage : ...
import Control.Monad ((>=>), (>>=), forM_) import Control.Monad.Primitive import qualified Data.Vector as V import qualified Data.Vector.Mutable as M import System.Random.MWC type MutVec m a = M.MVector (PrimState m) a cyclicPermM :: PrimMonad m => Gen (PrimState m) -> MutVec m a -> m (MutVec m a) cyclicPermM rand...
Produce a functionally identical Haskell code for the snippet given in C.
#include<stdlib.h> #include<stdio.h> #include<time.h> void sattoloCycle(void** arr,int count){ int i,j; void* temp; if(count<2) return; for(i=count-1;i>=1;i--){ j = rand()%i; temp = arr[j]; arr[j] = arr[i]; arr[i] = temp; } } int main(int argC,char* argV[]) { int i; if(argC==1) printf("Usage : ...
import Control.Monad ((>=>), (>>=), forM_) import Control.Monad.Primitive import qualified Data.Vector as V import qualified Data.Vector.Mutable as M import System.Random.MWC type MutVec m a = M.MVector (PrimState m) a cyclicPermM :: PrimMonad m => Gen (PrimState m) -> MutVec m a -> m (MutVec m a) cyclicPermM rand...
Translate this program into Haskell but keep the logic exactly as in C.
#include <ftplib.h> int main(void) { netbuf *nbuf; FtpInit(); FtpConnect("kernel.org", &nbuf); FtpLogin("anonymous", "", nbuf); FtpOptions(FTPLIB_CONNMODE, FTPLIB_PASSIVE, nbuf); FtpChdir("pub/linux/kernel", nbuf); FtpDir((void*)0, ".", nbuf); FtpGet("ftp.README", "README", FTPLIB_ASCI...
module Main (main) where import Control.Exception (bracket) import Control.Monad (void) import Data.Foldable (for_) import Network.FTP.Client ( cwd , easyConnectFTP , getbinary , loginAnon ...
Convert this C snippet to Haskell and keep its semantics consistent.
#include <stdio.h> #include <stdlib.h> #include <sqlite3.h> const char *code = "CREATE TABLE address (\n" " addrID INTEGER PRIMARY KEY AUTOINCREMENT,\n" " addrStreet TEXT NOT NULL,\n" " addrCity TEXT NOT NULL,\n" " addrState TEXT NOT NULL,\n" " addrZIP TEXT NOT NULL)\n" ; int main() { sqlite3 *db = NULL; ...
import Database.SQLite.Simple main = do db <- open "postal.db" execute_ db "\ \CREATE TABLE address (\ \addrID INTEGER PRIMARY KEY AUTOINCREMENT, \ \addrStreet TEXT NOT NULL, \ \addrCity TEXT NOT NULL, \ \addrState TEXT NOT NULL, \ \addrZIP TEXT NOT N...
Generate a Haskell translation of this C snippet without changing its computational steps.
#include <stdio.h> typedef char bool; #define TRUE 1 #define FALSE 0 bool same_digits(int n, int b) { int f = n % b; n /= b; while (n > 0) { if (n % b != f) return FALSE; n /= b; } return TRUE; } bool is_brazilian(int n) { int b; if (n < 7) return FALSE; if (!(n % 2) ...
import Data.Numbers.Primes (primes) isBrazil :: Int -> Bool isBrazil n = 7 <= n && (even n || any (monoDigit n) [2 .. n - 2]) monoDigit :: Int -> Int -> Bool monoDigit n b = let (q, d) = quotRem n b in d == snd (until (uncurry (flip ((||) . (d /=)) . (0 ==))) ((`quotRem` b) . fst) ...
Preserve the algorithm and functionality while converting the code from C to Haskell.
#include <stdio.h> typedef char bool; #define TRUE 1 #define FALSE 0 bool same_digits(int n, int b) { int f = n % b; n /= b; while (n > 0) { if (n % b != f) return FALSE; n /= b; } return TRUE; } bool is_brazilian(int n) { int b; if (n < 7) return FALSE; if (!(n % 2) ...
import Data.Numbers.Primes (primes) isBrazil :: Int -> Bool isBrazil n = 7 <= n && (even n || any (monoDigit n) [2 .. n - 2]) monoDigit :: Int -> Int -> Bool monoDigit n b = let (q, d) = quotRem n b in d == snd (until (uncurry (flip ((||) . (d /=)) . (0 ==))) ((`quotRem` b) . fst) ...
Produce a language-to-language conversion: from C to Haskell, same semantics.
#include<stdio.h> int main() { FILE* fp = fopen("TAPE.FILE","w"); fprintf(fp,"This code should be able to write a file to magnetic tape.\n"); fprintf(fp,"The Wikipedia page on Magnetic tape data storage shows that magnetic tapes are still in use.\n"); fprintf(fp,"In fact, the latest format, at the time of writin...
module Main (main) where main :: IO () main = writeFile "/dev/tape" "Hello from Rosetta Code!"
Please provide an equivalent version of this C code in Haskell.
#include <stdio.h> #include <stdlib.h> #include <gmodule.h> typedef int bool; int main() { int i, n, k = 0, next, *a; bool foundDup = FALSE; gboolean alreadyUsed; GHashTable* used = g_hash_table_new(g_direct_hash, g_direct_equal); GHashTable* used1000 = g_hash_table_new(g_direct_hash, g_direct_equ...
recaman :: Int -> [Int] recaman n = fst <$> reverse (go n) where go 0 = [] go 1 = [(0, 1)] go x = let xs@((r, i):_) = go (pred x) back = r - i in ( if 0 < back && not (any ((back ==) . fst) xs) then back else r + i , succ i) : ...
Ensure the translated Haskell code behaves exactly like the original C snippet.
#include <stdio.h> #include <stdlib.h> #include <gmodule.h> typedef int bool; int main() { int i, n, k = 0, next, *a; bool foundDup = FALSE; gboolean alreadyUsed; GHashTable* used = g_hash_table_new(g_direct_hash, g_direct_equal); GHashTable* used1000 = g_hash_table_new(g_direct_hash, g_direct_equ...
recaman :: Int -> [Int] recaman n = fst <$> reverse (go n) where go 0 = [] go 1 = [(0, 1)] go x = let xs@((r, i):_) = go (pred x) back = r - i in ( if 0 < back && not (any ((back ==) . fst) xs) then back else r + i , succ i) : ...
Write the same algorithm in Haskell as shown in this C implementation.
#include <stdio.h> #include <stdlib.h> typedef struct func_t *func; typedef struct func_t { func (*fn) (func, func); func _; int num; } func_t; func new(func(*f)(func, func), func _) { func x = malloc(sizeof(func_t)); x->fn = f; x->_ = _; x->num = 0; ...
newtype Mu a = Roll { unroll :: Mu a -> a } fix :: (a -> a) -> a fix = g <*> (Roll . g) where g = (. (>>= id) unroll) - this version is not in tail call position... fac :: Integer -> Integer fac = (fix $ \f n i -> if i <= 0 then n else f (i * n) (i - 1)) 1 { fibs :: () -> [Integer] fibs() = f...
Change the following C code into Haskell without altering its purpose.
#include <stdio.h> #include <stdlib.h> #include <math.h> #include <time.h> #include <stdbool.h> typedef double Fp; typedef struct { Fp x, y, r; } Circle; Circle circles[] = { { 1.6417233788, 1.6121789534, 0.0848270516}, {-1.4944608174, 1.2077959613, 1.1039549836}, { 0.6110294452, -0.6907087527, 0.908916...
data Circle = Circle { cx :: Double, cy :: Double, cr :: Double } isInside :: Double -> Double -> Circle -> Bool isInside x y c = (x - cx c) ^ 2 + (y - cy c) ^ 2 <= (cr c ^ 2) isInsideAny :: Double -> Double -> [Circle] -> Bool isInsideAny x y = any (isInside x y) approximatedArea :: [Circle] -> Int -> Double approx...
Preserve the algorithm and functionality while converting the code from C to Haskell.
#include <stdio.h> #include <stdlib.h> #include <math.h> #include <time.h> #include <stdbool.h> typedef double Fp; typedef struct { Fp x, y, r; } Circle; Circle circles[] = { { 1.6417233788, 1.6121789534, 0.0848270516}, {-1.4944608174, 1.2077959613, 1.1039549836}, { 0.6110294452, -0.6907087527, 0.908916...
data Circle = Circle { cx :: Double, cy :: Double, cr :: Double } isInside :: Double -> Double -> Circle -> Bool isInside x y c = (x - cx c) ^ 2 + (y - cy c) ^ 2 <= (cr c ^ 2) isInsideAny :: Double -> Double -> [Circle] -> Bool isInsideAny x y = any (isInside x y) approximatedArea :: [Circle] -> Int -> Double approx...
Change the programming language of this snippet from C to Haskell without modifying what it does.
#include <stdio.h> int main() { int n, b, d; unsigned long long i, j, sum, fact[12]; fact[0] = 1; for (n = 1; n < 12; ++n) { fact[n] = fact[n-1] * n; } for (b = 9; b <= 12; ++b) { printf("The factorions for base %d are:\n", b); for (i = 1; i < 1500000; ++i) { ...
import Text.Printf (printf) import Data.List (unfoldr) import Control.Monad (guard) factorion :: Int -> Int -> Bool factorion b n = f b n == n where f b = sum . map (product . enumFromTo 1) . unfoldr (\x -> guard (x > 0) >> pure (x `mod` b, x `div` b)) main :: IO () main = mapM_ (uncurry (printf "Factorions for ba...
Keep all operations the same but rewrite the snippet in Haskell.
#include <stdio.h> int main() { int n, b, d; unsigned long long i, j, sum, fact[12]; fact[0] = 1; for (n = 1; n < 12; ++n) { fact[n] = fact[n-1] * n; } for (b = 9; b <= 12; ++b) { printf("The factorions for base %d are:\n", b); for (i = 1; i < 1500000; ++i) { ...
import Text.Printf (printf) import Data.List (unfoldr) import Control.Monad (guard) factorion :: Int -> Int -> Bool factorion b n = f b n == n where f b = sum . map (product . enumFromTo 1) . unfoldr (\x -> guard (x > 0) >> pure (x `mod` b, x `div` b)) main :: IO () main = mapM_ (uncurry (printf "Factorions for ba...
Preserve the algorithm and functionality while converting the code from C to Haskell.
#include <stdio.h> unsigned int divisor_sum(unsigned int n) { unsigned int total = 1, power = 2; unsigned int p; for (; (n & 1) == 0; power <<= 1, n >>= 1) { total += power; } for (p = 3; p * p <= n; p += 2) { unsigned int sum = 1; for (power = p; n % p == 0; powe...
import Data.List.Split (chunksOf) divisors :: Integral a => a -> [a] divisors n = ((<>) <*> (rest . reverse . fmap (quot n))) $ filter ((0 ==) . rem n) [1 .. root] where root = (floor . sqrt . fromIntegral) n rest | n == root * root = tail | otherwise = id main :: IO () main = mapM_ ...
Convert this C block to Haskell, preserving its control flow and logic.
#include <stdio.h> unsigned int divisor_sum(unsigned int n) { unsigned int total = 1, power = 2; unsigned int p; for (; (n & 1) == 0; power <<= 1, n >>= 1) { total += power; } for (p = 3; p * p <= n; p += 2) { unsigned int sum = 1; for (power = p; n % p == 0; powe...
import Data.List.Split (chunksOf) divisors :: Integral a => a -> [a] divisors n = ((<>) <*> (rest . reverse . fmap (quot n))) $ filter ((0 ==) . rem n) [1 .. root] where root = (floor . sqrt . fromIntegral) n rest | n == root * root = tail | otherwise = id main :: IO () main = mapM_ ...
Keep all operations the same but rewrite the snippet in Haskell.
#include <stdio.h> #include <string.h> #include <stdlib.h> int interactiveCompare(const void *x1, const void *x2) { const char *s1 = *(const char * const *)x1; const char *s2 = *(const char * const *)x2; static int count = 0; printf("(%d) Is %s <, ==, or > %s? Answer -1, 0, or 1: ", ++count, s1, s2); int res...
import Control.Monad import Control.Monad.ListM (sortByM, insertByM, partitionM, minimumByM) import Data.Bool (bool) import Data.Monoid import Data.List isortM, msortM, tsortM :: Monad m => (a -> a -> m Ordering) -> [a] -> m [a] msortM = sortByM isortM cmp = foldM (flip (insertByM cmp)) [] tsortM cmp = go whe...
Translate this program into Haskell but keep the logic exactly as in C.
#include <stdlib.h> #include <stdio.h> #include <gmp.h> void mpz_factors(mpz_t n) { int factors = 0; mpz_t s, m, p; mpz_init(s), mpz_init(m), mpz_init(p); mpz_set_ui(m, 3); mpz_set(p, n); mpz_sqrt(s, p); while (mpz_cmp(m, s) < 0) { if (mpz_divisible_p(p, m)) { gmp_printf("%Zd ", m); mpz...
import Data.Numbers.Primes (primeFactors) import Data.Bool (bool) fermat :: Integer -> Integer fermat = succ . (2 ^) . (2 ^) fermats :: [Integer] fermats = fermat <$> [0 ..] main :: IO () main = mapM_ putStrLn [ fTable "First 10 Fermats:" show show fermat [0 .. 9] , fTable "Factors of first 7:...
Translate this program into Haskell but keep the logic exactly as in C.
#include <stdio.h> #include <stdlib.h> void bead_sort(int *a, int len) { int i, j, max, sum; unsigned char *beads; # define BEAD(i, j) beads[i * max + j] for (i = 1, max = a[0]; i < len; i++) if (a[i] > max) max = a[i]; beads = calloc(1, max * len); for (i = 0; i < len; i++) for (j = 0; j < a[i]; j++) ...
import Data.List beadSort :: [Int] -> [Int] beadSort = map sum. transpose. transpose. map (flip replicate 1)
Convert the following code from C to Haskell, ensuring the logic remains intact.
#include <stdio.h> #include <math.h> int main() { const int N = 2; int base = 10; int c1 = 0; int c2 = 0; int k; for (k = 1; k < pow(base, N); k++) { c1++; if (k % (base - 1) == (k * k) % (base - 1)) { c2++; printf("%d ", k); } } printf(...
co9 n | n <= 8 = n | otherwise = co9 $ sum $ filter (/= 9) $ digits 10 n task2 = filter (\n -> co9 n == co9 (n ^ 2)) [1 .. 100] task3 k = filter (\n -> n `mod` k == n ^ 2 `mod` k) [1 .. 100]
Convert this C block to Haskell, preserving its control flow and logic.
#include <stdio.h> #include <math.h> int main() { const int N = 2; int base = 10; int c1 = 0; int c2 = 0; int k; for (k = 1; k < pow(base, N); k++) { c1++; if (k % (base - 1) == (k * k) % (base - 1)) { c2++; printf("%d ", k); } } printf(...
co9 n | n <= 8 = n | otherwise = co9 $ sum $ filter (/= 9) $ digits 10 n task2 = filter (\n -> co9 n == co9 (n ^ 2)) [1 .. 100] task3 k = filter (\n -> n `mod` k == n ^ 2 `mod` k) [1 .. 100]
Change the programming language of this snippet from C to Haskell without modifying what it does.
#include <stdio.h> #include <stdlib.h> #include <string.h> #define _XOPEN_SOURCE #define __USE_XOPEN #include <time.h> #define DB "database.csv" #define TRY(a) if (!(a)) {perror(#a);exit(1);} #define TRY2(a) if((a)<0) {perror(#a);exit(1);} #define FREE(a) if(a) {free(a);a=NULL;} #define sort_by(foo) \ static int b...
import Control.Monad.State import Data.List (sortBy, nub) import System.Environment (getArgs, getProgName) import System.Directory (doesFileExist) import System.IO (openFile, hGetContents, hClose, IOMode(..), Handle, hPutStrLn) data Date = Date Integer Int Int deriving (Show, Read, Eq, Ord) data Item = Item ...
Convert the following code from C to Haskell, ensuring the logic remains intact.
#include <stdio.h> unsigned int divisor_count(unsigned int n) { unsigned int total = 1; for (; (n & 1) == 0; n >>= 1) { ++total; } for (unsigned int p = 3; p * p <= n; p += 2) { unsigned int count = 1; for (; n % p == 0; n /= p) { ++count; } ...
tau :: Integral a => a -> a tau n | n <= 0 = error "Not a positive integer" tau n = go 0 (1, 1) where yo i = (i, i * i) go r (i, ii) | n < ii = r | n == ii = r + 1 | 0 == mod n i = go (r + 2) (yo $ i + 1) | otherwise = go r (yo $ i + 1) main = print $ map tau [1..100]
Convert the following code from C to Haskell, ensuring the logic remains intact.
#include <stdio.h> unsigned int divisor_count(unsigned int n) { unsigned int total = 1; for (; (n & 1) == 0; n >>= 1) { ++total; } for (unsigned int p = 3; p * p <= n; p += 2) { unsigned int count = 1; for (; n % p == 0; n /= p) { ++count; } ...
tau :: Integral a => a -> a tau n | n <= 0 = error "Not a positive integer" tau n = go 0 (1, 1) where yo i = (i, i * i) go r (i, ii) | n < ii = r | n == ii = r + 1 | 0 == mod n i = go (r + 2) (yo $ i + 1) | otherwise = go r (yo $ i + 1) main = print $ map tau [1..100]
Generate a Haskell translation of this C snippet without changing its computational steps.
#include <math.h> #include <stdio.h> #include <stdlib.h> #include <string.h> int main() { const int MU_MAX = 1000000; int i, j; int *mu; int sqroot; sqroot = (int)sqrt(MU_MAX); mu = malloc((MU_MAX + 1) * sizeof(int)); for (i = 0; i < MU_MAX;i++) { mu[i] = 1; } for (i = 2...
import Data.List (intercalate) import Data.List.Split (chunksOf) import Data.Vector.Unboxed (toList) import Math.NumberTheory.ArithmeticFunctions.Moebius (Moebius(..), sieveBlockMoebius) import System.Environment (getArgs, getProgName) import System.IO (hPutStrLn, s...
Change the programming language of this snippet from C to Haskell without modifying what it does.
#include <stdio.h> int Gcd(int v1, int v2) { int a, b, r; if (v1 < v2) { a = v2; b = v1; } else { a = v1; b = v2; } do { r = a % b; if (r == 0) { break; } else { a = b; b = r; } } while (1 == 1); return b; } int NotInList(int num, int numtrip, int *tripletslist) { for...
import Data.List (find, transpose, unfoldr) import Data.List.Split (chunksOf) import qualified Data.Set as S coprimeTriples :: Integral a => [a] coprimeTriples = [1, 2] <> unfoldr go (S.fromList [1, 2], (1, 2)) where go (seen, (a, b)) = Just (c, (S.insert c seen, (b, c))) where Ju...
Can you help me rewrite this code in Haskell instead of C, keeping it the same logically?
#include <stdio.h> int Gcd(int v1, int v2) { int a, b, r; if (v1 < v2) { a = v2; b = v1; } else { a = v1; b = v2; } do { r = a % b; if (r == 0) { break; } else { a = b; b = r; } } while (1 == 1); return b; } int NotInList(int num, int numtrip, int *tripletslist) { for...
import Data.List (find, transpose, unfoldr) import Data.List.Split (chunksOf) import qualified Data.Set as S coprimeTriples :: Integral a => [a] coprimeTriples = [1, 2] <> unfoldr go (S.fromList [1, 2], (1, 2)) where go (seen, (a, b)) = Just (c, (S.insert c seen, (b, c))) where Ju...
Preserve the algorithm and functionality while converting the code from C to Haskell.
#include <stdio.h> #include <stdbool.h> #include <stdint.h> #include <locale.h> uint64_t modPow(uint64_t base, uint64_t exp, uint64_t mod) { if (mod == 1) return 0; uint64_t result = 1; base %= mod; for (; exp > 0; exp >>= 1) { if ((exp & 1) == 1) result = (result * base) % mod; base = ...
import Data.List.Split ( chunksOf ) isGeneralizedCurzon :: Integer -> Integer -> Bool isGeneralizedCurzon base n = mod ( base ^ n + 1 ) ( base * n + 1 ) == 0 solution :: Integer -> [Integer] solution base = take 50 $ filter (\i -> isGeneralizedCurzon base i ) [1..] printChunk :: [Integer] -> String printChunk chunk ...
Change the following C code into Haskell without altering its purpose.
#include <stdio.h> #include <stdbool.h> #include <stdint.h> #include <locale.h> uint64_t modPow(uint64_t base, uint64_t exp, uint64_t mod) { if (mod == 1) return 0; uint64_t result = 1; base %= mod; for (; exp > 0; exp >>= 1) { if ((exp & 1) == 1) result = (result * base) % mod; base = ...
import Data.List.Split ( chunksOf ) isGeneralizedCurzon :: Integer -> Integer -> Bool isGeneralizedCurzon base n = mod ( base ^ n + 1 ) ( base * n + 1 ) == 0 solution :: Integer -> [Integer] solution base = take 50 $ filter (\i -> isGeneralizedCurzon base i ) [1..] printChunk :: [Integer] -> String printChunk chunk ...
Convert this C snippet to Haskell and keep its semantics consistent.
#include <stdio.h> #include <stdlib.h> int* mertens_numbers(int max) { int* m = malloc((max + 1) * sizeof(int)); if (m == NULL) return m; m[1] = 1; for (int n = 2; n <= max; ++n) { m[n] = 1; for (int k = 2; k <= n; ++k) m[n] -= m[n/k]; } return m; } int main...
import Data.List.Split (chunksOf) import qualified Data.MemoCombinators as Memo import Math.NumberTheory.Primes (unPrime, factorise) import Text.Printf (printf) moebius :: Integer -> Int moebius = product . fmap m . factorise where m (p, e) | unPrime p =...
Write the same algorithm in Haskell as shown in this C implementation.
#include <math.h> #include <stdio.h> unsigned int divisor_count(unsigned int n) { unsigned int total = 1; unsigned int p; for (; (n & 1) == 0; n >>= 1) { ++total; } for (p = 3; p * p <= n; p += 2) { unsigned int count = 1; for (; n % p == 0; n /= p) { ...
import Data.List.Split (chunksOf) divisors :: Integral a => a -> [a] divisors n = ((<>) <*> (rest . reverse . fmap (quot n))) $ filter ((0 ==) . rem n) [1 .. root] where root = (floor . sqrt . fromIntegral) n rest | n == root * root = tail | otherwise = id main :: IO () main = mapM_ ...
Ensure the translated Haskell code behaves exactly like the original C snippet.
#include <math.h> #include <stdio.h> unsigned int divisor_count(unsigned int n) { unsigned int total = 1; unsigned int p; for (; (n & 1) == 0; n >>= 1) { ++total; } for (p = 3; p * p <= n; p += 2) { unsigned int count = 1; for (; n % p == 0; n /= p) { ...
import Data.List.Split (chunksOf) divisors :: Integral a => a -> [a] divisors n = ((<>) <*> (rest . reverse . fmap (quot n))) $ filter ((0 ==) . rem n) [1 .. root] where root = (floor . sqrt . fromIntegral) n rest | n == root * root = tail | otherwise = id main :: IO () main = mapM_ ...
Produce a language-to-language conversion: from C to Haskell, same semantics.
#include <stdio.h> #include <stdlib.h> #include <locale.h> int locale_ok = 0; wchar_t s_suits[] = L"♠♥♦♣"; const char *s_suits_ascii[] = { "S", "H", "D", "C" }; const char *s_nums[] = { "WHAT", "A", "2", "3", "4", "5", "6", "7", "8", "9", "10", "J", "Q", "K", "OVERFLOW" }; typedef struct { int suit, number, _s;...
import System.Random data Pip = Two | Three | Four | Five | Six | Seven | Eight | Nine | Ten | Jack | Queen | King | Ace deriving (Ord, Enum, Bounded, Eq, Show) data Suit = Diamonds | Spades | Hearts | Clubs deriving (Ord, Enum, Bounded, Eq, Show) type Card = (Pip, Suit) fullRange :: (Bounded a, En...
Keep all operations the same but rewrite the snippet in Haskell.
#include <stdio.h> int gcd(int a, int b) { int c; while (b) { c = a; a = b; b = c % b; } return a; } struct pair { int x, y; }; void printPair(struct pair const *p) { printf("{%d, %d}\n", p->x, p->y); } int main() { struct pair pairs[] = { {21,15}, {17,23}...
coprime :: Integral a => a -> a -> Bool coprime a b = 1 == gcd a b main :: IO () main = print $ filter ((1 ==) . uncurry gcd) [ (21, 15), (17, 23), (36, 12), (18, 29), (60, 15) ]
Generate a Haskell translation of this C snippet without changing its computational steps.
#include <stdio.h> int gcd(int a, int b) { int c; while (b) { c = a; a = b; b = c % b; } return a; } struct pair { int x, y; }; void printPair(struct pair const *p) { printf("{%d, %d}\n", p->x, p->y); } int main() { struct pair pairs[] = { {21,15}, {17,23}...
coprime :: Integral a => a -> a -> Bool coprime a b = 1 == gcd a b main :: IO () main = print $ filter ((1 ==) . uncurry gcd) [ (21, 15), (17, 23), (36, 12), (18, 29), (60, 15) ]
Preserve the algorithm and functionality while converting the code from C to Haskell.
#include<stdlib.h> #include<stdio.h> long totient(long n){ long tot = n,i; for(i=2;i*i<=n;i+=2){ if(n%i==0){ while(n%i==0) n/=i; tot-=tot/i; } if(i==2) i=1; } if(n>1) tot-=tot/n; return tot; } long* perfectTotients(long n){ long *ptList = (long*)malloc(n*sizeof(long)), m,count=0,su...
perfectTotients :: [Int] perfectTotients = filter ((==) <*> (succ . sum . tail . takeWhile (1 /=) . iterate φ)) [2 ..] φ :: Int -> Int φ = memoize (\n -> length (filter ((1 ==) . gcd n) [1 .. n])) memoize :: (Int -> a) -> (Int -> a) memoize f = (!!) (f <$> [0 ..]) main :: IO () main = print $ take 20 perfectTotien...
Port the following code from C to Haskell with equivalent syntax and logic.
#include<stdlib.h> #include<stdio.h> long totient(long n){ long tot = n,i; for(i=2;i*i<=n;i+=2){ if(n%i==0){ while(n%i==0) n/=i; tot-=tot/i; } if(i==2) i=1; } if(n>1) tot-=tot/n; return tot; } long* perfectTotients(long n){ long *ptList = (long*)malloc(n*sizeof(long)), m,count=0,su...
perfectTotients :: [Int] perfectTotients = filter ((==) <*> (succ . sum . tail . takeWhile (1 /=) . iterate φ)) [2 ..] φ :: Int -> Int φ = memoize (\n -> length (filter ((1 ==) . gcd n) [1 .. n])) memoize :: (Int -> a) -> (Int -> a) memoize f = (!!) (f <$> [0 ..]) main :: IO () main = print $ take 20 perfectTotien...
Translate the given C code snippet into Haskell without altering its behavior.
#include <stdint.h> #include <stdio.h> uint64_t factorial(uint64_t n) { uint64_t res = 1; if (n == 0) return res; while (n > 0) res *= n--; return res; } uint64_t lah(uint64_t n, uint64_t k) { if (k == 1) return factorial(n); if (k == n) return 1; if (k > n) return 0; if (k < 1 || n < ...
import Text.Printf (printf) import Control.Monad (when) factorial :: Integral n => n -> n factorial 0 = 1 factorial n = product [1..n] lah :: Integral n => n -> n -> n lah n k | k == 1 = factorial n | k == n = 1 | k > n = 0 | k < 1 || n < 1 = 0 | otherwise = f n `div` f k `div` factorial (n - k) wh...
Maintain the same structure and functionality when rewriting this code in Haskell.
#include <stdint.h> #include <stdio.h> uint64_t factorial(uint64_t n) { uint64_t res = 1; if (n == 0) return res; while (n > 0) res *= n--; return res; } uint64_t lah(uint64_t n, uint64_t k) { if (k == 1) return factorial(n); if (k == n) return 1; if (k > n) return 0; if (k < 1 || n < ...
import Text.Printf (printf) import Control.Monad (when) factorial :: Integral n => n -> n factorial 0 = 1 factorial n = product [1..n] lah :: Integral n => n -> n -> n lah n k | k == 1 = factorial n | k == n = 1 | k > n = 0 | k < 1 || n < 1 = 0 | otherwise = f n `div` f k `div` factorial (n - k) wh...
Maintain the same structure and functionality when rewriting this code in Haskell.
#include<stdio.h> int main() { int arr[5] = {0, 2, 11, 19, 90},sum = 21,i,j,check = 0; for(i=0;i<4;i++){ for(j=i+1;j<5;j++){ if(arr[i]+arr[j]==sum){ printf("[%d,%d]",i,j); check = 1; break; } } } if(check==0) printf("[]"); return 0; }
twoSum::(Num a,Ord a) => a -> [a] -> [Int] twoSum num list = sol ls (reverse ls) where ls = zip list [0..] sol [] _ = [] sol _ [] = [] sol xs@((x,i):us) ys@((y,j):vs) = ans where s = x + y ans | s == num = [i,j] | j <= i = [] | s < num = sol (dropWhile ((<num).(+y).fst) us) y...
Change the programming language of this snippet from C to Haskell without modifying what it does.
#include<stdio.h> int main() { int arr[5] = {0, 2, 11, 19, 90},sum = 21,i,j,check = 0; for(i=0;i<4;i++){ for(j=i+1;j<5;j++){ if(arr[i]+arr[j]==sum){ printf("[%d,%d]",i,j); check = 1; break; } } } if(check==0) printf("[]"); return 0; }
twoSum::(Num a,Ord a) => a -> [a] -> [Int] twoSum num list = sol ls (reverse ls) where ls = zip list [0..] sol [] _ = [] sol _ [] = [] sol xs@((x,i):us) ys@((y,j):vs) = ans where s = x + y ans | s == num = [i,j] | j <= i = [] | s < num = sol (dropWhile ((<num).(+y).fst) us) y...
Generate a Haskell translation of this C snippet without changing its computational steps.
#include<stdlib.h> #include<stdio.h> int main () { int i; char *str = getenv ("LANG"); for (i = 0; str[i + 2] != 00; i++) { if ((str[i] == 'u' && str[i + 1] == 't' && str[i + 2] == 'f') || (str[i] == 'U' && str[i + 1] == 'T' && str[i + 2] == 'F')) { printf ("Uni...
import System.Environment import Data.List import Data.Char import Data.Maybe main = do x <- mapM lookupEnv ["LANG", "LC_ALL", "LC_CTYPE"] if any (isInfixOf "UTF". map toUpper) $ catMaybes x then putStrLn "UTF supported: \x25b3" else putStrLn "UTF not supported"
Port the following code from C to Haskell with equivalent syntax and logic.
#include<stdlib.h> #include<stdio.h> int main () { int i; char *str = getenv ("LANG"); for (i = 0; str[i + 2] != 00; i++) { if ((str[i] == 'u' && str[i + 1] == 't' && str[i + 2] == 'f') || (str[i] == 'U' && str[i + 1] == 'T' && str[i + 2] == 'F')) { printf ("Uni...
import System.Environment import Data.List import Data.Char import Data.Maybe main = do x <- mapM lookupEnv ["LANG", "LC_ALL", "LC_CTYPE"] if any (isInfixOf "UTF". map toUpper) $ catMaybes x then putStrLn "UTF supported: \x25b3" else putStrLn "UTF not supported"
Keep all operations the same but rewrite the snippet in Haskell.
#include <assert.h> #include <locale.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)...
import Control.Lens ((.~), ix, (&)) import Data.Numbers.Primes (isPrime) import Data.List (find, intercalate) import Data.Char (intToDigit) import Data.Maybe (mapMaybe) import Data.List.Split (chunksOf) import Text.Printf (printf) isUnprimable :: Int -> Bool isUnprimable = all (not . isPrime) . swapdigits swapdigits ...
Convert this C block to Haskell, preserving its control flow and logic.
#include <stdio.h> unsigned int divisor_count(unsigned int n) { unsigned int total = 1; unsigned int p; for (; (n & 1) == 0; n >>= 1) { ++total; } for (p = 3; p * p <= n; p += 2) { unsigned int count = 1; for (; n % p == 0; n /= p) { ++count; }...
tau :: Integral a => a -> a tau n | n <= 0 = error "Not a positive integer" tau n = go 0 (1, 1) where yo i = (i, i * i) go r (i, ii) | n < ii = r | n == ii = r + 1 | 0 == mod n i = go (r + 2) (yo $ i + 1) | otherwise = go r (yo $ i + 1) isTau :: Integral a => a -> Bool isTau...
Translate the given C code snippet into Haskell without altering its behavior.
#include <stdbool.h> #include <stdio.h> bool is_prime(int n) { int i = 5; if (n < 2) { return false; } if (n % 2 == 0) { return n == 2; } if (n % 3 == 0) { return n == 3; } while (i * i <= n) { if (n % i == 0) { return false; } ...
import Data.Bifunctor (second) import Data.List (replicate) import Data.List.Split (chunksOf) import Data.Numbers.Primes (primes) matchingPrimes :: [Int] matchingPrimes = takeWhile (< 5000) [n | n <- primes, 25 == decimalDigitSum n] decimalDigitSum :: Int -> Int decimalDigitSum n = snd $ until ...
Convert this C block to Haskell, preserving its control flow and logic.
#include <stdbool.h> #include <stdio.h> bool is_prime(int n) { int i = 5; if (n < 2) { return false; } if (n % 2 == 0) { return n == 2; } if (n % 3 == 0) { return n == 3; } while (i * i <= n) { if (n % i == 0) { return false; } ...
import Data.Bifunctor (second) import Data.List (replicate) import Data.List.Split (chunksOf) import Data.Numbers.Primes (primes) matchingPrimes :: [Int] matchingPrimes = takeWhile (< 5000) [n | n <- primes, 25 == decimalDigitSum n] decimalDigitSum :: Int -> Int decimalDigitSum n = snd $ until ...
Generate an equivalent Haskell version of this C code.
#include <stdbool.h> #include <stdio.h> bool primeDigitsSum13(int n) { int sum = 0; while (n > 0) { int r = n % 10; switch (r) { case 2: case 3: case 5: case 7: break; default: return false; } n /= 10; sum +...
import Data.List.Split (chunksOf) import Data.List (intercalate, transpose, unfoldr) import Text.Printf primeDigitsNumsSummingToN :: Int -> [Int] primeDigitsNumsSummingToN n = concat $ unfoldr go (return <$> primeDigits) where primeDigits = [2, 3, 5, 7] go :: [[Int]] -> Maybe ([Int], [[Int]]) go xs ...
Produce a language-to-language conversion: from C to Haskell, same semantics.
#include <stdbool.h> #include <stdio.h> bool primeDigitsSum13(int n) { int sum = 0; while (n > 0) { int r = n % 10; switch (r) { case 2: case 3: case 5: case 7: break; default: return false; } n /= 10; sum +...
import Data.List.Split (chunksOf) import Data.List (intercalate, transpose, unfoldr) import Text.Printf primeDigitsNumsSummingToN :: Int -> [Int] primeDigitsNumsSummingToN n = concat $ unfoldr go (return <$> primeDigits) where primeDigits = [2, 3, 5, 7] go :: [[Int]] -> Maybe ([Int], [[Int]]) go xs ...
Translate this program into Haskell but keep the logic exactly as in C.
#include <stdbool.h> #include <stdint.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <gmp.h> bool is_prime(uint32_t n) { if (n == 2) return true; if (n < 2 || n % 2 == 0) return false; for (uint32_t p = 3; p * p <= n; p += 2) { if (n % p == 0) ret...
import Math.NumberTheory.Primes (Prime, unPrime, nextPrime) import Math.NumberTheory.Primes.Testing (isPrime, millerRabinV) import Text.Printf (printf) rotated :: [Integer] -> [Integer] rotated xs | any (< head xs) xs = [] | otherwise = map asNum $ take (pred $ length xs) $ rotate xs where rotate [] =...
Write a version of this C function in Haskell with identical behavior.
#include <stdio.h> #include <stdlib.h> #include <math.h> #define LIMIT 10000 unsigned int sieve(unsigned int n, unsigned int **list) { unsigned char *sieve = calloc(n+1, 1); unsigned int i, j, max = 0; for (i = 2; i*i <= n; i++) if (!sieve[i]) for (j = i+i; j <= n; j += i) ...
primes = 2 : sieve [3,5..] where sieve (x:xs) = x : sieve (filter (\y -> y `mod` x /= 0) xs) frobenius = zipWith (\a b -> a*b - a - b) primes (tail primes)
Generate an equivalent Haskell version of this C code.
#include <stdio.h> #include <stdlib.h> #include <math.h> #define LIMIT 10000 unsigned int sieve(unsigned int n, unsigned int **list) { unsigned char *sieve = calloc(n+1, 1); unsigned int i, j, max = 0; for (i = 2; i*i <= n; i++) if (!sieve[i]) for (j = i+i; j <= n; j += i) ...
primes = 2 : sieve [3,5..] where sieve (x:xs) = x : sieve (filter (\y -> y `mod` x /= 0) xs) frobenius = zipWith (\a b -> a*b - a - b) primes (tail primes)
Port the provided C code into Haskell while preserving the original functionality.
#include <stdio.h> #include <stdlib.h> #include <string.h> typedef int(*cmp_func)(const void*, const void*); void perm_sort(void *a, int n, size_t msize, cmp_func _cmp) { char *p, *q, *tmp = malloc(msize); # define A(i) ((char *)a + msize * (i)) # define swap(a, b) {\ memcpy(tmp, a, msize);\ memcpy(a, b, msize);...
import Control.Monad permutationSort l = head [p | p <- permute l, sorted p] sorted (e1 : e2 : r) = e1 <= e2 && sorted (e2 : r) sorted _ = True permute = foldM (flip insert) [] insert e [] = return [e] insert e l@(h : t) = return (e : l) `mplus` do { t' <- ...
Write a version of this C function in Haskell with identical behavior.
#include <stdio.h> #include <math.h> typedef unsigned long long ulong; ulong root(ulong base, ulong n) { ulong n1, n2, n3, c, d, e; if (base < 2) return base; if (n == 0) return 1; n1 = n - 1; n2 = n; n3 = n1; c = 1; d = (n3 + base) / n2; e = (n3 * d + base / (ulong)powl(d, n1)) ...
root :: Integer -> Integer -> Integer root a b = findAns $ iterate (\x -> (a1 * x + b `div` (x ^ a1)) `div` a) 1 where a1 = a - 1 findAns (x:xs@(y:z:_)) | x == y || x == z = min y z | otherwise = findAns xs main :: IO () main = do print $ root 3 8 print $ root 3 9 print $ root 2 (2 * 100 ^ ...
Transform the following C implementation into Haskell, maintaining the same output and logic.
#include <stdio.h> #include <math.h> typedef unsigned long long ulong; ulong root(ulong base, ulong n) { ulong n1, n2, n3, c, d, e; if (base < 2) return base; if (n == 0) return 1; n1 = n - 1; n2 = n; n3 = n1; c = 1; d = (n3 + base) / n2; e = (n3 * d + base / (ulong)powl(d, n1)) ...
root :: Integer -> Integer -> Integer root a b = findAns $ iterate (\x -> (a1 * x + b `div` (x ^ a1)) `div` a) 1 where a1 = a - 1 findAns (x:xs@(y:z:_)) | x == y || x == z = min y z | otherwise = findAns xs main :: IO () main = do print $ root 3 8 print $ root 3 9 print $ root 2 (2 * 100 ^ ...
Preserve the algorithm and functionality while converting the code from C to Haskell.
#include <stdio.h> #include <stdlib.h> #include <stdbool.h> #include <gmp.h> 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[1] = true; for (i = 4; i < limit; i += 2) c[i] = true; p = 3; ...
import Data.Numbers.Primes (primes) import Math.NumberTheory.Primes.Testing (isPrime) import Data.List (nub) primorials :: [Integer] primorials = 1 : scanl1 (*) primes nextPrime :: Integer -> Integer nextPrime n | even n = head $ dropWhile (not . isPrime) [n+1, n+3..] | even n = nextPrime (n+1) fortunateNumbers ...
Preserve the algorithm and functionality while converting the code from C to Haskell.
int meaning_of_life();
#!/usr/bin/env runhaskell module ScriptedMain where meaningOfLife :: Int meaningOfLife = 42 main :: IO () main = putStrLn $ "Main: The meaning of life is " ++ show meaningOfLife
Rewrite this program in Haskell while keeping its functionality equivalent to the C version.
int meaning_of_life();
#!/usr/bin/env runhaskell module ScriptedMain where meaningOfLife :: Int meaningOfLife = 42 main :: IO () main = putStrLn $ "Main: The meaning of life is " ++ show meaningOfLife
Rewrite the snippet below in Haskell so it works the same as the original C code.
#define _POSIX_SOURCE #include <ctype.h> #include <stdio.h> #include <stdlib.h> #include <errno.h> #include <string.h> #include <stddef.h> #include <sys/mman.h> #include <sys/types.h> #include <sys/stat.h> #include <unistd.h> struct functionInfo { char* name; int timesCalled; char marked; }; void addToList(...
import Language.Haskell.Parser (parseModule) import Data.List.Split (splitOn) import Data.List (nub, sortOn, elemIndices) findApps src = freq $ concat [apps, comps] where ast = show $ parseModule src apps = extract <$> splitApp ast comps = extract <$> concat (splitComp <$> splitInfix ast) splitApp = ...
Write the same algorithm in Haskell as shown in this C implementation.
#include <stdbool.h> #include <stdio.h> bool is_prime(unsigned int n) { if (n < 2) { return false; } if (n % 2 == 0) { return n == 2; } if (n % 3 == 0) { return n == 3; } for (unsigned int p = 5; p * p <= n; p += 4) { if (n % p == 0) { return fals...
import Data.Char ( digitToInt ) 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 digitsum :: Int -> Int digitsum n = sum $ map digitToInt $ show n findSumn :: I...
Convert this C block to Haskell, preserving its control flow and logic.
#include <stdbool.h> #include <stdio.h> bool is_prime(unsigned int n) { if (n < 2) { return false; } if (n % 2 == 0) { return n == 2; } if (n % 3 == 0) { return n == 3; } for (unsigned int p = 5; p * p <= n; p += 4) { if (n % p == 0) { return fals...
import Data.Char ( digitToInt ) 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 digitsum :: Int -> Int digitsum n = sum $ map digitToInt $ show n findSumn :: I...
Keep all operations the same but rewrite the snippet in Haskell.
#include <stdio.h> #include <stdlib.h> int main(int argc, char *argv[]) { int days[] = {31,29,31,30,31,30,31,31,30,31,30,31}; int m, y, w; if (argc < 2 || (y = atoi(argv[1])) <= 1752) return 1; days[1] -= (y % 4) || (!(y % 100) && (y % 400)); w = y * 365 + 97 * (y - 1) / 400 + ...
import Data.List (find, intercalate, transpose) import Data.Maybe (fromJust) import Data.Time.Calendar ( Day, addDays, fromGregorian, gregorianMonthLength, showGregorian, ) import Data.Time.Calendar.WeekDate (toWeekDate) lastSundayOfEachMonth = lastWeekDayDates 7 main :: IO () main = mapM_ ...
Convert the following code from C to Haskell, ensuring the logic remains intact.
#include <stdio.h> #include <stdlib.h> int main(int argc, char *argv[]) { int days[] = {31,29,31,30,31,30,31,31,30,31,30,31}; int m, y, w; if (argc < 2 || (y = atoi(argv[1])) <= 1752) return 1; days[1] -= (y % 4) || (!(y % 100) && (y % 400)); w = y * 365 + 97 * (y - 1) / 400 + ...
import Data.List (find, intercalate, transpose) import Data.Maybe (fromJust) import Data.Time.Calendar ( Day, addDays, fromGregorian, gregorianMonthLength, showGregorian, ) import Data.Time.Calendar.WeekDate (toWeekDate) lastSundayOfEachMonth = lastWeekDayDates 7 main :: IO () main = mapM_ ...
Generate a Haskell translation of this C snippet without changing its computational steps.
#include <stdbool.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <time.h> int randInt(int low, int high) { return (rand() % (high - low)) + low; } void shuffle(int *const array, const int n) { if (n > 1) { int i; for (i = 0; i < n - 1; i++) { int j = randI...
import Data.List (permutations, (\\)) latinSquare :: Eq a => [a] -> [a] -> [[a]] latinSquare [] [] = [] latinSquare c r | head r /= head c = [] | otherwise = reverse <$> foldl addRow firstRow perms where perms = tail $ fmap (fmap . (:) <*> (permutations . (r \\) . return)) ...
Preserve the algorithm and functionality while converting the code from C to Haskell.
#include <stdbool.h> #include <stdio.h> #include <stdlib.h> #include <glib.h> int string_compare(gconstpointer p1, gconstpointer p2) { const char* const* s1 = p1; const char* const* s2 = p2; return strcmp(*s1, *s2); } GPtrArray* load_dictionary(const char* file, GError** error_ptr) { GError* error = N...
import Data.List (groupBy, intercalate, sort, sortBy) import qualified Data.Set as S import Data.Ord (comparing) import Data.Function (on) main :: IO () main = readFile "mitWords.txt" >>= (putStrLn . showGroups . circularWords . lines) circularWords :: [String] -> [String] circularWords ws = let lexicon = S.fromL...
Convert this C block to Haskell, preserving its control flow and logic.
#include <stdio.h> #include <stdlib.h> int turn(int base, int n) { int sum = 0; while (n != 0) { int rem = n % base; n = n / base; sum += rem; } return sum % base; } void fairshare(int base, int count) { int i; printf("Base %2d:", base); for (i = 0; i < count; i++)...
import Data.Bool (bool) import Data.List (intercalate, unfoldr) import Data.Tuple (swap) thueMorse :: Int -> [Int] thueMorse base = baseDigitsSumModBase base <$> [0 ..] baseDigitsSumModBase :: Int -> Int -> Int baseDigitsSumModBase base n = mod ( sum $ unfoldr ( bool Nothing . ...
Write a version of this C function in Haskell with identical behavior.
#include <stdio.h> #include <string.h> #include <locale.h> typedef int bool; typedef unsigned long long ull; #define TRUE 1 #define FALSE 0 char as_digit(int d) { return (d >= 0 && d <= 9) ? d + '0' : d - 10 + 'a'; } void revstr(char *str) { int i, len = strlen(str); char t; for (i = 0; i < le...
import Data.List (unfoldr, genericIndex) import Control.Monad (replicateM, foldM, mzero) isEsthetic b = all ((== 1) . abs) . differences . toBase b where differences lst = zipWith (-) lst (tail lst) esthetics_m b = do differences <- (\n -> replicateM n [-1, 1]) <$> [0..] firstDigit <- [1..b-1] dif...
Write the same algorithm in Haskell as shown in this C implementation.
#include<stdlib.h> #include<string.h> #include<stdio.h> int flag = 1; void heapPermute(int n, int arr[],int arrLen){ int temp; int i; if(n==1){ printf("\n["); for(i=0;i<arrLen;i++) printf("%d,",arr[i]); printf("\b] Sign : %d",flag); flag*=-1; } else{ for(i=0;i<n-1;i++){ heapPermute(n-1,ar...
sPermutations :: [a] -> [([a], Int)] sPermutations = flip zip (cycle [-1, 1]) . foldr aux [[]] where aux x items = do (f, item) <- zip (repeat id) items f (insertEv x item) insertEv x [] = [[x]] insertEv x l@(y:ys) = (x : l) : ((y :) <$> insertEv x ys) main :: IO () main = do putStrLn "3 it...
Generate an equivalent Haskell version of this C code.
#include <stdio.h> #include <stdlib.h> #include <time.h> int compareInts(const void *i1, const void *i2) { int a = *((int *)i1); int b = *((int *)i2); return a - b; } int main() { int i, j, nsum, vsum, vcount, values[6], numbers[4]; srand(time(NULL)); for (;;) { vsum = 0; for (...
import Control.Monad (replicateM) import System.Random (randomRIO) import Data.Bool (bool) import Data.List (sort) character :: IO [Int] character = discardUntil (((&&) . (75 <) . sum) <*> ((2 <=) . length . filter (15 <=))) (replicateM 6 $ sum . tail . sort <$> replicateM 4 (randomRIO (1, 6 :: Int))) disca...
Rewrite this program in Haskell while keeping its functionality equivalent to the C version.
#include <stdio.h> #include <stdlib.h> #define TRUE 1 #define FALSE 0 typedef int bool; int next_in_cycle(int *c, int len, int index) { return c[index % len]; } void kolakoski(int *c, int *s, int clen, int slen) { int i = 0, j, k = 0; while (TRUE) { s[i] = next_in_cycle(c, clen, k); if (...
import Data.List (group) import Control.Monad (forM_) replicateAtLeastOne :: Int -> a -> [a] replicateAtLeastOne n x = x : replicate (n-1) x zipWithLazy :: (a -> b -> c) -> [a] -> [b] -> [c] zipWithLazy f ~(x:xs) ~(y:ys) = f x y : zipWithLazy f xs ys kolakoski :: [Int] -> [Int] kolakoski items = s where s = concat...
Ensure the translated Haskell code behaves exactly like the original C snippet.
#include <stdio.h> #define MAX 15 int count_divisors(int n) { int i, count = 0; for (i = 1; i * i <= n; ++i) { if (!(n % i)) { if (i == n / i) count++; else count += 2; } } return count; } int main() { int i, k, n, seq[MAX]; ...
import Data.List (find, group, sort) import Data.Maybe (mapMaybe) import Data.Numbers.Primes (primeFactors) a005179 :: [Int] a005179 = mapMaybe ( \n -> find ((n ==) . succ . length . properDivisors) [1 ..] ) [1 ..] main :: IO () main = print $ take 15 a005179 properDivi...
Port the following code from C to Haskell with equivalent syntax and logic.
#include<string.h> #include<stdlib.h> #include<locale.h> #include<stdio.h> #include<wchar.h> #include<math.h> int main(int argC,char* argV[]) { double* arr,min,max; char* str; int i,len; if(argC == 1) printf("Usage : %s <data points separated by spaces or commas>",argV[0]); else{ arr = (double*)malloc((argC-1...
import Data.List.Split (splitOneOf) import Data.Char (chr) toSparkLine :: [Double] -> String toSparkLine xs = map cl xs where top = maximum xs bot = minimum xs range = top - bot cl x = chr $ 0x2581 + floor (min 7 ((x - bot) / range * 8)) makeSparkLine :: String -> (String, Stats) makeSparkLine xs =...
Please provide an equivalent version of this C code in Haskell.
#include <stdio.h> #include <stdlib.h> #include <string.h> typedef struct edit_s edit_t, *edit; struct edit_s { char c1, c2; int n; edit next; }; void leven(char *a, char *b) { int i, j, la = strlen(a), lb = strlen(b); edit *tbl = malloc(sizeof(edit) * (1 + la)); tbl[0] = calloc((1 + la) * (1 + lb), sizeof(edit...
costs :: String -> String -> [[Int]] costs s1 s2 = reverse $ reverse <$> matrix where matrix = scanl transform [0 .. length s1] s2 transform ns@(n:ns1) c = scanl calc (n + 1) $ zip3 s1 ns ns1 where calc z (c1, x, y) = minimum [ y + 1, z + 1 , x + fromEnum (c1 ...
Translate the given C code snippet into Haskell without altering its behavior.
#include <stdio.h> #include <stdlib.h> struct node { int val, len; struct node *next; }; void lis(int *v, int len) { int i; struct node *p, *n = calloc(len, sizeof *n); for (i = 0; i < len; i++) n[i].val = v[i]; for (i = len; i--; ) { for (p = n + i; p++ < n + len; ) { if (p->val > n[i].val && p->len...
import Data.Ord ( comparing ) import Data.List ( maximumBy, subsequences ) import Data.List.Ordered ( isSorted, nub ) lis :: Ord a => [a] -> [a] lis = maximumBy (comparing length) . map nub . filter isSorted . subsequences main = do print $ lis [3,2,6,4,5,1] print $ lis [0,8,4,...
Change the programming language of this snippet from C to Haskell without modifying what it does.
#include <stdio.h> #include <math.h> int main() { int i, p, low, high, pow = 1, osc; int oddSq[120]; for (p = 0; p < 5; ++p) { low = (int)ceil(sqrt((double)pow)); if (!(low%2)) ++low; pow *= 10; high = (int)sqrt((double)pow); for (i = low, osc = 0; i <= high; i += 2)...
main :: IO () main = print $ takeWhile (<1000) $ filter odd $ map (^2) $ [10..]
Ensure the translated Haskell code behaves exactly like the original C snippet.
#include <stdio.h> #include <stdbool.h> int digit_sum(int n) { int sum; for (sum = 0; n; n /= 10) sum += n % 10; return sum; } bool prime(int n) { if (n<4) return n>=2; for (int d=2; d*d <= n; d++) if (n%d == 0) return false; return true; } int main() { for (int i=1; i<100; i++) ...
import Data.Bifunctor (first) import Data.Numbers.Primes (isPrime) p :: Int -> Bool p = ((&&) . primeDigitSum . (^ 2)) <*> (primeDigitSum . (^ 3)) main :: IO () main = print $ filter p [2 .. 99] primeDigitSum :: Int -> Bool primeDigitSum = isPrime . digitSum 10 digitSum :: Int -> Int -> Int digitSum base ...
Write a version of this C function in Haskell with identical behavior.
i code = True let u x = x x (this code not compiled) Are you? -} i code = True i code = True
Please provide an equivalent version of this C code in Haskell.
#include <stdio.h> #include <wchar.h> #include <stdlib.h> #include <locale.h> int main(void) { char *locale = setlocale(LC_ALL, ""); FILE *in = fopen("input.txt", "r"); wint_t c; while ((c = fgetwc(in)) != WEOF) putwchar(c); fclose(in); return EXIT_SUCCESS; }
#!/usr/bin/env runhaskell import System.Environment (getArgs) import System.IO ( Handle, IOMode (..), hGetChar, hIsEOF, hSetEncoding, stdin, utf8, withFile ) import Control.Monad (forM_, unless) import Text.Printf (printf) import Data.Char (ord) processCharacters :: Handle -> IO () processCharac...
Translate the given C code snippet into Haskell without altering its behavior.
#include <stdio.h> #include <stdlib.h> #include <string.h> #define BALLS 1024 int n, w, h = 45, *x, *y, cnt = 0; char *b; #define B(y, x) b[(y)*w + x] #define C(y, x) ' ' == b[(y)*w + x] #define V(i) B(y[i], x[i]) inline int rnd(int a) { return (rand()/(RAND_MAX/a))%a; } void show_board() { int i, j; for (puts("\0...
import Data.Map hiding (map, filter) import Graphics.Gloss import Control.Monad.Random data Ball = Ball { position :: (Int, Int), turns :: [Int] } type World = ( Int , [Ball] , Map Int Int ) updateWorld :: World -> World updateWorld (nRows, balls, bins) | y < -nRows-5 ...
Preserve the algorithm and functionality while converting the code from C to Haskell.
#include <math.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #define MAXPRIME 99 #define MAXPARENT 99 #define NBRPRIMES 30 #define NBRANCESTORS 10 FILE *FileOut; char format[] = ", %lld"; int Primes[NBRPRIMES]; int iPrimes; short Ancestors[NBRANCESTORS]; struct C...
import Data.Numbers.Primes (isPrime) import Data.List type Memo2 a = Memo (Memo a) 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 :: Integral a => Memo ...
Rewrite this program in Haskell while keeping its functionality equivalent to the C version.
#include <stdio.h> void f(int n) { int i = 1; if (n < 1) { return; } while (1) { int sq = i * i; while (sq > n) { sq /= 10; } if (sq == n) { printf("%3d %9d %4d\n", n, i * i, i); return; } i++; } } int main...
import Control.Monad (join) import Data.List (find, intercalate, isPrefixOf, transpose) import Data.List.Split (chunksOf) import Text.Printf (printf) firstSquareWithPrefix :: Int -> Int firstSquareWithPrefix n = unDigits match where ds = digits n Just match = find (isPrefixOf ds) squareDigits squareDigits...
Change the programming language of this snippet from C to Haskell without modifying what it does.
#include <stdio.h> void f(int n) { int i = 1; if (n < 1) { return; } while (1) { int sq = i * i; while (sq > n) { sq /= 10; } if (sq == n) { printf("%3d %9d %4d\n", n, i * i, i); return; } i++; } } int main...
import Control.Monad (join) import Data.List (find, intercalate, isPrefixOf, transpose) import Data.List.Split (chunksOf) import Text.Printf (printf) firstSquareWithPrefix :: Int -> Int firstSquareWithPrefix n = unDigits match where ds = digits n Just match = find (isPrefixOf ds) squareDigits squareDigits...
Produce a language-to-language conversion: from C to Haskell, same semantics.
#include <stdio.h> int circle_sort_inner(int *start, int *end) { int *p, *q, t, swapped; if (start == end) return 0; for (swapped = 0, p = start, q = end; p<q || (p==q && ++q); p++, q--) if (*p > *q) t = *p, *p = *q, *q = t, swapped = 1; return swapped | circle_sort_inner(start, q) | circle_sort_inner(...
import Data.Bool (bool) circleSort :: Ord a => [a] -> [a] circleSort xs = if swapped then circleSort ks else ks where (swapped,ks) = go False xs (False,[]) go d [] sks = sks go d [x] (s,ks) = (s,x:ks) go d xs (s,ks) = let (st,_,ls,rs) = halve d s xs xs in go False ls (go True rs (s...
Ensure the translated Haskell code behaves exactly like the original C snippet.
#include <stdbool.h> #include <stdio.h> #define MAX_WORD 80 #define LETTERS 26 bool is_letter(char c) { return c >= 'a' && c <= 'z'; } int index(char c) { return c - 'a'; } void word_wheel(const char* letters, char central, int min_length, FILE* dict) { int max_count[LETTERS] = { 0 }; for (const char* p = l...
import Data.Char (toLower) import Data.List (sort) import System.IO (readFile) gridWords :: [String] -> [String] -> [String] gridWords grid = filter ( ((&&) . (2 <) . length) <*> (((&&) . elem mid) <*> wheelFit wheel) ) where cs = toLower <$> concat grid wheel = sort cs mid = cs !! 4 ...
Rewrite this program in Haskell while keeping its functionality equivalent to the C version.
#include <stdbool.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #define BUFFER_SIZE 128 typedef unsigned char character; typedef character *string; typedef struct node_t node; struct node_t { enum tag_t { NODE_LEAF, NODE_TREE, NODE_SEQ, } tag; union { stri...
import qualified Text.Parsec as P showExpansion :: String -> String showExpansion = (<>) . (<> "\n parser :: P.Parsec String u [String] parser = expansion P.anyChar expansion :: P.Parsec String u Char -> P.Parsec String u [String] expansion = fmap expand . P.many . ((P.try alts P.<|> P.try alt1 P.<|> escape)...