Instruction
stringlengths
45
106
input_code
stringlengths
1
13.7k
output_code
stringlengths
1
13.7k
Ensure the translated Haskell code behaves exactly like the original C++ snippet.
#include <iostream> #include <sstream> #include <set> bool checkDec(int num) { std::set<int> set; std::stringstream ss; ss << num; auto str = ss.str(); for (int i = 0; i < str.size(); ++i) { char c = str[i]; int d = c - '0'; if (d == 0) return false; if (num % d !=...
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] ...
Translate the given C++ code snippet into Haskell without altering its behavior.
#include <iostream> #include <sstream> #include <set> bool checkDec(int num) { std::set<int> set; std::stringstream ss; ss << num; auto str = ss.str(); for (int i = 0; i < str.size(); ++i) { char c = str[i]; int d = c - '0'; if (d == 0) return false; if (num % d !=...
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] ...
Can you help me rewrite this code in Haskell instead of C++, keeping it the same logically?
#include <algorithm> #include <cassert> #include <iomanip> #include <iostream> int jacobi(int n, int k) { assert(k > 0 && k % 2 == 1); n %= k; int t = 1; while (n != 0) { while (n % 2 == 0) { n /= 2; int r = k % 8; if (r == 3 || r == 5) t = -t...
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 the same code in Haskell as shown below in C++.
#include <algorithm> #include <cassert> #include <iomanip> #include <iostream> int jacobi(int n, int k) { assert(k > 0 && k % 2 == 1); n %= k; int t = 1; while (n != 0) { while (n % 2 == 0) { n /= 2; int r = k % 8; if (r == 3 || r == 5) t = -t...
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 ...
Generate an equivalent Haskell version of this C++ code.
#include <iostream> int digitSum(int n) { int s = 0; do {s += n % 10;} while (n /= 10); return s; } int main() { for (int i=0; i<1000; i++) { auto s_i = std::to_string(i); auto s_ds = std::to_string(digitSum(i)); if (s_i.find(s_ds) != std::string::npos) { std::cout ...
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 :...
Convert the following code from C++ to Haskell, ensuring the logic remains intact.
#include <iostream> int digitSum(int n) { int s = 0; do {s += n % 10;} while (n /= 10); return s; } int main() { for (int i=0; i<1000; i++) { auto s_i = std::to_string(i); auto s_ds = std::to_string(digitSum(i)); if (s_i.find(s_ds) != std::string::npos) { std::cout ...
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 :...
Rewrite this program in Haskell while keeping its functionality equivalent to the C++ version.
#include <ctime> #include <string> #include <iostream> #include <algorithm> class cycle{ public: template <class T> void cy( T* a, int len ) { int i, j; show( "original: ", a, len ); std::srand( unsigned( time( 0 ) ) ); for( int i = len - 1; i > 0; i-- ) { do { ...
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...
Write the same code in Haskell as shown below in C++.
#include <ctime> #include <string> #include <iostream> #include <algorithm> class cycle{ public: template <class T> void cy( T* a, int len ) { int i, j; show( "original: ", a, len ); std::srand( unsigned( time( 0 ) ) ); for( int i = len - 1; i > 0; i-- ) { do { ...
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 <iostream> #include <string> #include <cstring> #include <fstream> #include <sys/stat.h> #include <ftplib.h> #include <ftp++.hpp> int stat(const char *pathname, struct stat *buf); char *strerror(int errnum); char *basename(char *path); namespace stl { using std::cout; ...
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 <iostream> bool sameDigits(int n, int b) { int f = n % b; while ((n /= b) > 0) { if (n % b != f) { return false; } } return true; } bool isBrazilian(int n) { if (n < 7) return false; if (n % 2 == 0)return true; for (int b = 2; b < n - 1; b++) { ...
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) ...
Convert the following code from C++ to Haskell, ensuring the logic remains intact.
#include <iostream> bool sameDigits(int n, int b) { int f = n % b; while ((n /= b) > 0) { if (n % b != f) { return false; } } return true; } bool isBrazilian(int n) { if (n < 7) return false; if (n % 2 == 0)return true; for (int b = 2; b < n - 1; b++) { ...
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) ...
Port the following code from C++ to Haskell with equivalent syntax and logic.
#include <iostream> #include <fstream> #if defined(_WIN32) || defined(WIN32) constexpr auto FILENAME = "tape.file"; #else constexpr auto FILENAME = "/dev/tape"; #endif int main() { std::filebuf fb; fb.open(FILENAME,std::ios::out); std::ostream os(&fb); os << "Hello World\n"; fb.close(); return...
module Main (main) where main :: IO () main = writeFile "/dev/tape" "Hello from Rosetta Code!"
Preserve the algorithm and functionality while converting the code from C++ to Haskell.
#include <iostream> #include <ostream> #include <set> #include <vector> template<typename T> std::ostream& operator<<(std::ostream& os, const std::vector<T>& v) { auto i = v.cbegin(); auto e = v.cend(); os << '['; if (i != e) { os << *i; i = std::next(i); } while (i != e) { ...
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) : ...
Maintain the same structure and functionality when rewriting this code in Haskell.
#include <iostream> #include <ostream> #include <set> #include <vector> template<typename T> std::ostream& operator<<(std::ostream& os, const std::vector<T>& v) { auto i = v.cbegin(); auto e = v.cend(); os << '['; if (i != e) { os << *i; i = std::next(i); } while (i != e) { ...
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) : ...
Keep all operations the same but rewrite the snippet in Haskell.
#include <iostream> #include <functional> template <typename F> struct RecursiveFunc { std::function<F(RecursiveFunc)> o; }; template <typename A, typename B> std::function<B(A)> Y (std::function<std::function<B(A)>(std::function<B(A)>)> f) { RecursiveFunc<std::function<B(A)>> r = { std::function<std::function<B(...
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...
Maintain the same structure and functionality when rewriting this code in Haskell.
#include <iostream> class factorion_t { public: factorion_t() { f[0] = 1u; for (uint n = 1u; n < 12u; n++) f[n] = f[n - 1] * n; } bool operator()(uint i, uint b) const { uint sum = 0; for (uint j = i; j > 0u; j /= b) sum += f[j % b]; return s...
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...
Convert this C++ snippet to Haskell and keep its semantics consistent.
#include <iostream> class factorion_t { public: factorion_t() { f[0] = 1u; for (uint n = 1u; n < 12u; n++) f[n] = f[n - 1] * n; } bool operator()(uint i, uint b) const { uint sum = 0; for (uint j = i; j > 0u; j /= b) sum += f[j % b]; return s...
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...
Can you help me rewrite this code in Haskell instead of C++, keeping it the same logically?
#include <iomanip> #include <iostream> unsigned int divisor_sum(unsigned int n) { unsigned int total = 1, power = 2; for (; (n & 1) == 0; power <<= 1, n >>= 1) total += power; for (unsigned int p = 3; p * p <= n; p += 2) { unsigned int sum = 1; for (power = p; n % p == 0;...
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_ ...
Translate the given C++ code snippet into Haskell without altering its behavior.
#include <iomanip> #include <iostream> unsigned int divisor_sum(unsigned int n) { unsigned int total = 1, power = 2; for (; (n & 1) == 0; power <<= 1, n >>= 1) total += power; for (unsigned int p = 3; p * p <= n; p += 2) { unsigned int sum = 1; for (power = p; n % p == 0;...
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_ ...
Transform the following C++ implementation into Haskell, maintaining the same output and logic.
#include <algorithm> #include <iostream> #include <vector> using namespace std; bool InteractiveCompare(const string& s1, const string& s2) { if(s1 == s2) return false; static int count = 0; string response; cout << "(" << ++count << ") Is " << s1 << " < " << s2 << "? "; getline(cin, response); ...
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...
Rewrite this program in Haskell while keeping its functionality equivalent to the C++ version.
#include <iostream> #include <vector> #include <boost/integer/common_factor.hpp> #include <boost/multiprecision/cpp_int.hpp> #include <boost/multiprecision/miller_rabin.hpp> typedef boost::multiprecision::cpp_int integer; integer fermat(unsigned int n) { unsigned int p = 1; for (unsigned int i = 0; i < n; ++i...
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:...
Change the programming language of this snippet from C++ to Haskell without modifying what it does.
#include <iostream> #include <vector> using std::cout; using std::vector; void distribute(int dist, vector<int> &List) { if (dist > List.size() ) List.resize(dist); for (int i=0; i < dist; i++) List[i]++; } vector<int> beadSort(int *myints, int n) { vector<int> list, list2, fifth ...
import Data.List beadSort :: [Int] -> [Int] beadSort = map sum. transpose. transpose. map (flip replicate 1)
Port the provided C++ code into Haskell while preserving the original functionality.
#include <iostream> int main() { int Base = 10; const int N = 2; int c1 = 0; int c2 = 0; for (int k=1; k<pow((double)Base,N); k++){ c1++; if (k%(Base-1) == (k*k)%(Base-1)){ c2++; std::cout << k << " "; } } std::cout << "\nTrying " << c2 << " numbers instead of " << c1 << " numbers saves " << 100 ...
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 <iostream> int main() { int Base = 10; const int N = 2; int c1 = 0; int c2 = 0; for (int k=1; k<pow((double)Base,N); k++){ c1++; if (k%(Base-1) == (k*k)%(Base-1)){ c2++; std::cout << k << " "; } } std::cout << "\nTrying " << c2 << " numbers instead of " << c1 << " numbers saves " << 100 ...
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]
Port the following code from C++ to Haskell with equivalent syntax and logic.
#include <iomanip> #include <iostream> 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 an equivalent Haskell version of this C++ code.
#include <iomanip> #include <iostream> 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]
Can you help me rewrite this code in Haskell instead of C++, keeping it the same logically?
#include <iomanip> #include <iostream> #include <vector> constexpr int MU_MAX = 1'000'000; std::vector<int> MU; int mobiusFunction(int n) { if (!MU.empty()) { return MU[n]; } MU.resize(MU_MAX + 1, 1); int root = sqrt(MU_MAX); for (int i = 2; i <= root; i++) { if (MU[i] == 1)...
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...
Rewrite this program in Haskell while keeping its functionality equivalent to the C++ version.
#include <cstdint> #include <iomanip> #include <iostream> #include <vector> 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;...
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 programming language of this snippet from C++ to Haskell without modifying what it does.
#include <cstdint> #include <iomanip> #include <iostream> #include <vector> 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;...
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 ...
Rewrite the snippet below in Haskell so it works the same as the original C++ code.
#include <iomanip> #include <iostream> #include <vector> std::vector<int> mertens_numbers(int max) { std::vector<int> m(max + 1, 1); for (int n = 2; n <= max; ++n) { for (int k = 2; k <= n; ++k) m[n] -= m[n / k]; } return m; } int main() { const int max = 1000; auto m(merte...
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 =...
Maintain the same structure and functionality when rewriting this code in Haskell.
#include <cmath> #include <iomanip> #include <iostream> 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) ...
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_ ...
Change the programming language of this snippet from C++ to Haskell without modifying what it does.
#include <cmath> #include <iomanip> #include <iostream> 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) ...
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_ ...
Write the same algorithm in Haskell as shown in this C++ implementation.
#include <deque> #include <algorithm> #include <ostream> #include <iterator> namespace cards { class card { public: enum pip_type { two, three, four, five, six, seven, eight, nine, ten, jack, queen, king, ace, pip_count }; enum suite_type { hearts, spades, diamonds, clubs, suite_count }; ...
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...
Change the following C++ code into Haskell without altering its purpose.
#include <iostream> #include <algorithm> #include <vector> #include <utility> int gcd(int a, int b) { int c; while (b) { c = a; a = b; b = c % b; } return a; } int main() { using intpair = std::pair<int,int>; std::vector<intpair> pairs = { {21,15}, {17,23}, {36,...
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) ]
Convert this C++ block to Haskell, preserving its control flow and logic.
#include <iostream> #include <algorithm> #include <vector> #include <utility> int gcd(int a, int b) { int c; while (b) { c = a; a = b; b = c % b; } return a; } int main() { using intpair = std::pair<int,int>; std::vector<intpair> pairs = { {21,15}, {17,23}, {36,...
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) ]
Write the same algorithm in Haskell as shown in this C++ implementation.
#include <cassert> #include <iostream> #include <vector> class totient_calculator { public: explicit totient_calculator(int max) : totient_(max + 1) { for (int i = 1; i <= max; ++i) totient_[i] = i; for (int i = 2; i <= max; ++i) { if (totient_[i] < i) contin...
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...
Change the programming language of this snippet from C++ to Haskell without modifying what it does.
#include <cassert> #include <iostream> #include <vector> class totient_calculator { public: explicit totient_calculator(int max) : totient_(max + 1) { for (int i = 1; i <= max; ++i) totient_[i] = i; for (int i = 2; i <= max; ++i) { if (totient_[i] < i) contin...
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...
Rewrite the snippet below in Haskell so it works the same as the original C++ code.
#include <algorithm> #include <iomanip> #include <iostream> #include <map> #include <gmpxx.h> using integer = mpz_class; class unsigned_lah_numbers { public: integer get(int n, int k); private: std::map<std::pair<int, int>, integer> cache_; }; integer unsigned_lah_numbers::get(int n, int k) { if (k == ...
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...
Translate the given C++ code snippet into Haskell without altering its behavior.
#include <algorithm> #include <iomanip> #include <iostream> #include <map> #include <gmpxx.h> using integer = mpz_class; class unsigned_lah_numbers { public: integer get(int n, int k); private: std::map<std::pair<int, int>, integer> cache_; }; integer unsigned_lah_numbers::get(int n, int k) { if (k == ...
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...
Convert this C++ snippet to Haskell and keep its semantics consistent.
#include <iostream> #include <map> #include <tuple> #include <vector> using namespace std; pair<int, int> twoSum(vector<int> numbers, int sum) { auto m = map<int, int>(); for (size_t i = 0; i < numbers.size(); ++i) { auto key = sum - numbers[i]; if (m.find(key) != m.end()) { return make_pair(m[key], i); ...
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...
Rewrite the snippet below in Haskell so it works the same as the original C++ code.
#include <iostream> #include <map> #include <tuple> #include <vector> using namespace std; pair<int, int> twoSum(vector<int> numbers, int sum) { auto m = map<int, int>(); for (size_t i = 0; i < numbers.size(); ++i) { auto key = sum - numbers[i]; if (m.find(key) != m.end()) { return make_pair(m[key], i); ...
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...
Translate the given C++ code snippet into Haskell without altering its behavior.
#include <iostream> #include <cstdint> #include "prime_sieve.hpp" typedef uint32_t integer; int count_digits(integer n) { int digits = 0; for (; n > 0; ++digits) n /= 10; return digits; } integer change_digit(integer n, int index, int new_digit) { integer p = 1; integer changed = 0; ...
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 ...
Change the programming language of this snippet from C++ to Haskell without modifying what it does.
#include <iomanip> #include <iostream> 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) isTau :: Integral a => a -> Bool isTau...
Convert this C++ block to Haskell, preserving its control flow and logic.
#include <algorithm> #include <chrono> #include <iomanip> #include <iostream> #include <string> #include <gmpxx.h> bool is_probably_prime(const mpz_class& n) { return mpz_probab_prime_p(n.get_mpz_t(), 3) != 0; } bool is_prime(int n) { if (n < 2) return false; if (n % 2 == 0) return n == 2...
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 <algorithm> #include <chrono> #include <iomanip> #include <iostream> #include <string> #include <gmpxx.h> bool is_probably_prime(const mpz_class& n) { return mpz_probab_prime_p(n.get_mpz_t(), 3) != 0; } bool is_prime(int n) { if (n < 2) return false; if (n % 2 == 0) return n == 2...
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 ...
Ensure the translated Haskell code behaves exactly like the original C++ snippet.
#include <cstdio> #include <vector> #include <bits/stdc++.h> using namespace std; int main() { vector<tuple<int, int>> w; int lst[4] = { 2, 3, 5, 7 }, sum; for (int x : lst) w.push_back({x, x}); while (w.size() > 0) { auto i = w[0]; w.erase(w.begin()); for (int x : lst) if ((sum = get<1>(i) + x) == 13) ...
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 ...
Convert the following code from C++ to Haskell, ensuring the logic remains intact.
#include <cstdio> #include <vector> #include <bits/stdc++.h> using namespace std; int main() { vector<tuple<int, int>> w; int lst[4] = { 2, 3, 5, 7 }, sum; for (int x : lst) w.push_back({x, x}); while (w.size() > 0) { auto i = w[0]; w.erase(w.begin()); for (int x : lst) if ((sum = get<1>(i) + x) == 13) ...
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 ...
Change the programming language of this snippet from C++ to Haskell without modifying what it does.
#include <cstdint> #include <algorithm> #include <iostream> #include <sstream> #include <gmpxx.h> typedef mpz_class integer; bool is_prime(const integer& n, int reps = 50) { return mpz_probab_prime_p(n.get_mpz_t(), reps); } std::string to_string(const integer& n) { std::ostringstream out; out << n; r...
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 [] =...
Produce a functionally identical Haskell code for the snippet given in C++.
#include <cstdint> #include <iomanip> #include <iostream> #include <primesieve.hpp> 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) r...
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)
Transform the following C++ implementation into Haskell, maintaining the same output and logic.
#include <cstdint> #include <iomanip> #include <iostream> #include <primesieve.hpp> 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) r...
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 a Haskell translation of this C++ snippet without changing its computational steps.
#include <algorithm> template<typename ForwardIterator> void permutation_sort(ForwardIterator begin, ForwardIterator end) { while (std::next_permutation(begin, end)) { } }
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' <- ...
Change the following C++ code into Haskell without altering its purpose.
#include <iostream> #include <math.h> unsigned long long root(unsigned long long base, unsigned int n) { if (base < 2) return base; if (n == 0) return 1; unsigned int n1 = n - 1; unsigned long long n2 = n; unsigned long long n3 = n1; unsigned long long c = 1; auto d = (n3 + base) / n2; auto e = (n3 * d + base...
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 <iostream> #include <math.h> unsigned long long root(unsigned long long base, unsigned int n) { if (base < 2) return base; if (n == 0) return 1; unsigned int n1 = n - 1; unsigned long long n2 = n; unsigned long long n3 = n1; unsigned long long c = 1; auto d = (n3 + base) / n2; auto e = (n3 * d + base...
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 ^ ...
Convert this C++ snippet to Haskell and keep its semantics consistent.
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
Generate an equivalent Haskell version of this C++ code.
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
Convert this C++ block to Haskell, preserving its control flow and logic.
#include <iostream> 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 false; p += 2; if (n % p == 0) ...
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...
Rewrite this program in Haskell while keeping its functionality equivalent to the C++ version.
#include <windows.h> #include <iostream> #include <string> using namespace std; class lastSunday { public: lastSunday() { m[0] = "JANUARY: "; m[1] = "FEBRUARY: "; m[2] = "MARCH: "; m[3] = "APRIL: "; m[4] = "MAY: "; m[5] = "JUNE: "; m[6] = "JULY: "; m[7] = "AUGUST: ";...
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 <windows.h> #include <iostream> #include <string> using namespace std; class lastSunday { public: lastSunday() { m[0] = "JANUARY: "; m[1] = "FEBRUARY: "; m[2] = "MARCH: "; m[3] = "APRIL: "; m[4] = "MAY: "; m[5] = "JUNE: "; m[6] = "JULY: "; m[7] = "AUGUST: ";...
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_ ...
Produce a functionally identical Haskell code for the snippet given in C++.
#include <algorithm> #include <chrono> #include <iostream> #include <random> #include <vector> template <typename T> std::ostream &operator<<(std::ostream &os, const std::vector<T> &v) { auto it = v.cbegin(); auto end = v.cend(); os << '['; if (it != end) { os << *it; it = std::next(it...
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)) ...
Write the same code in Haskell as shown below in C++.
#include <algorithm> #include <fstream> #include <iostream> #include <set> #include <string> #include <vector> std::set<std::string> load_dictionary(const std::string& filename) { std::ifstream in(filename); if (!in) throw std::runtime_error("Cannot open file " + filename); std::set<std::string> w...
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 the following code from C++ to Haskell, ensuring the logic remains intact.
#include <iostream> #include <vector> 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) { printf("Base %2d:", base); for (int 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 . ...
Generate a Haskell translation of this C++ snippet without changing its computational steps.
#include <functional> #include <iostream> #include <sstream> #include <vector> std::string to(int n, int b) { static auto BASE = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"; std::stringstream ss; while (n > 0) { auto rem = n % b; n = n / b; ss << BASE[rem]; } auto fwd = ss.str(...
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...
Preserve the algorithm and functionality while converting the code from C++ to Haskell.
#include <iostream> #include <vector> using namespace std; vector<int> UpTo(int n, int offset = 0) { vector<int> retval(n); for (int ii = 0; ii < n; ++ii) retval[ii] = ii + offset; return retval; } struct JohnsonTrotterState_ { vector<int> values_; vector<int> positions_; vector<bool> directions_; int sign...
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...
Ensure the translated Haskell code behaves exactly like the original C++ snippet.
#include <algorithm> #include <ctime> #include <iostream> #include <cstdlib> #include <string> using namespace std; int main() { srand(time(0)); unsigned int attributes_total = 0; unsigned int count = 0; int attributes[6] = {}; int rolls[4] = {}; while(attributes_total < 75 || count ...
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...
Transform the following C++ implementation into Haskell, maintaining the same output and logic.
#include <iostream> #include <vector> using Sequence = std::vector<int>; std::ostream& operator<<(std::ostream& os, const Sequence& v) { os << "[ "; for (const auto& e : v) { std::cout << e << ", "; } os << "]"; return os; } int next_in_cycle(const Sequence& s, size_t i) { return s[i % s.size()]; } ...
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...
Translate the given C++ code snippet into Haskell without altering its behavior.
#include <iostream> #define MAX 15 using namespace std; int count_divisors(int n) { int count = 0; for (int i = 1; i * i <= n; ++i) { if (!(n % i)) { if (i == n / i) count++; else count += 2; } } return count; } int main() { ...
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...
Translate this program into Haskell but keep the logic exactly as in C++.
#include <iostream> #include <sstream> #include <vector> #include <cmath> #include <algorithm> #include <locale> class Sparkline { public: Sparkline(std::wstring &cs) : charset( cs ){ } virtual ~Sparkline(){ } void print(std::string spark){ const char *delim = "...
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 =...
Rewrite the snippet below in Haskell so it works the same as the original C++ code.
#include <vector> #include <list> #include <algorithm> #include <iostream> template <typename T> struct Node { T value; Node* prev_node; }; template <typename Container> Container lis(const Container& values) { using E = typename Container::value_type; using NodePtr = Node<E>*; using ConstNodePtr ...
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,...
Write the same code in Haskell as shown below in C++.
#include <algorithm> #include <chrono> #include <iomanip> #include <iostream> #include <locale> #include <vector> #include <primesieve.hpp> auto get_primes_by_digits(uint64_t limit) { primesieve::iterator pi; std::vector<std::vector<uint64_t>> primes_by_digits; std::vector<uint64_t> primes; for (uint6...
import Control.Monad (join) import Data.Bifunctor (bimap) import Data.List (intercalate, transpose) import Data.List.Split (chunksOf, splitWhen) import Data.Numbers.Primes (primeFactors) import Text.Printf (printf) isBrilliant :: (Integral a, Show a) => a -> Bool isBrilliant n = case primeFactors n of [a, b] -> le...
Ensure the translated Haskell code behaves exactly like the original C++ snippet.
#include <algorithm> #include <chrono> #include <iomanip> #include <iostream> #include <locale> #include <vector> #include <primesieve.hpp> auto get_primes_by_digits(uint64_t limit) { primesieve::iterator pi; std::vector<std::vector<uint64_t>> primes_by_digits; std::vector<uint64_t> primes; for (uint6...
import Control.Monad (join) import Data.Bifunctor (bimap) import Data.List (intercalate, transpose) import Data.List.Split (chunksOf, splitWhen) import Data.Numbers.Primes (primeFactors) import Text.Printf (printf) isBrilliant :: (Integral a, Show a) => a -> Bool isBrilliant n = case primeFactors n of [a, b] -> le...
Rewrite the snippet below in Haskell so it works the same as the original C++ code.
#include <iostream> #include <vector> #include <boost/rational.hpp> using rational = boost::rational<unsigned long>; unsigned long floor(const rational& r) { return r.numerator()/r.denominator(); } rational calkin_wilf_next(const rational& term) { return 1UL/(2UL * floor(term) + 1UL - term); } std::vector<u...
import Control.Monad (forM_) import Data.Bool (bool) import Data.List.NonEmpty (NonEmpty, fromList, toList, unfoldr) import Text.Printf (printf) calkinWilfs :: [Rational] calkinWilfs = iterate (recip . succ . ((-) =<< (2 *) . fromIntegral . floor)) 1 calkinWilfIdx :: Rational -> Integer calkinWilfIdx = rld . cfo ...
Change the following C++ code into Haskell without altering its purpose.
#include <iostream> #include <vector> #include <boost/rational.hpp> using rational = boost::rational<unsigned long>; unsigned long floor(const rational& r) { return r.numerator()/r.denominator(); } rational calkin_wilf_next(const rational& term) { return 1UL/(2UL * floor(term) + 1UL - term); } std::vector<u...
import Control.Monad (forM_) import Data.Bool (bool) import Data.List.NonEmpty (NonEmpty, fromList, toList, unfoldr) import Text.Printf (printf) calkinWilfs :: [Rational] calkinWilfs = iterate (recip . succ . ((-) =<< (2 *) . fromIntegral . floor)) 1 calkinWilfIdx :: Rational -> Integer calkinWilfIdx = rld . cfo ...
Please provide an equivalent version of this C++ code in Haskell.
#include <iostream> #include <vector> #include <algorithm> #include <string> template <typename T> void print(const std::vector<T> v) { std::cout << "{ "; for (const auto& e : v) { std::cout << e << " "; } std::cout << "}"; } template <typename T> auto orderDisjointArrayItems(std::vector<T> M, std::vector...
import Data.List (mapAccumL, sort) order :: Ord a => [[a]] -> [a] order [ms, ns] = snd . mapAccumL yu ls $ ks where ks = zip ms [(0 :: Int) ..] ls = zip ns . sort . snd . foldl go (sort ns, []) . sort $ ks yu ((u, v):us) (_, y) | v == y = (us, u) yu ys (x, _) = (ys, x) go (u:us, ys) (x,...
Rewrite this program in Haskell while keeping its functionality equivalent to the C++ version.
#include <algorithm> #include <cmath> #include <iomanip> #include <iostream> #include <string> unsigned int reverse(unsigned int base, unsigned int n) { unsigned int rev = 0; for (; n > 0; n /= base) rev = rev * base + (n % base); return rev; } class palindrome_generator { public: explicit pal...
import Data.Numbers.Primes palindromicPrimes :: [Integer] palindromicPrimes = filter (((==) <*> reverse) . show) primes main :: IO () main = mapM_ print $ takeWhile (1000 >) palindromicPrimes
Preserve the algorithm and functionality while converting the code from C++ to Haskell.
#include <algorithm> #include <cmath> #include <iomanip> #include <iostream> #include <string> unsigned int reverse(unsigned int base, unsigned int n) { unsigned int rev = 0; for (; n > 0; n /= base) rev = rev * base + (n % base); return rev; } class palindrome_generator { public: explicit pal...
import Data.Numbers.Primes palindromicPrimes :: [Integer] palindromicPrimes = filter (((==) <*> reverse) . show) primes main :: IO () main = mapM_ print $ takeWhile (1000 >) palindromicPrimes
Translate the given C++ code snippet into Haskell without altering its behavior.
#include <iomanip> #include <iostream> #include <boost/rational.hpp> #include <boost/multiprecision/cpp_int.hpp> using integer = boost::multiprecision::cpp_int; using rational = boost::rational<integer>; integer sylvester_next(const integer& n) { return n * n - n + 1; } int main() { std::cout << "First 10 el...
sylvester :: [Integer] sylvester = map s [0 ..] where s 0 = 2 s n = succ $ foldr ((*) . s) 1 [0 .. pred n] main :: IO () main = do putStrLn "First 10 elements of Sylvester's sequence:" putStr $ unlines $ map show $ take 10 sylvester putStr "\nSum of reciprocals by sum over map: " print $ sum $ map (...
Produce a language-to-language conversion: from C++ to Haskell, same semantics.
#include <iomanip> #include <iostream> #include <boost/rational.hpp> #include <boost/multiprecision/gmp.hpp> using integer = boost::multiprecision::mpz_int; using rational = boost::rational<integer>; class harmonic_generator { public: rational next() { rational result = term_; term_ += rational(1,...
import Data.List (find) import Data.Ratio harmonic :: [Rational] harmonic = scanl1 (\a x -> a + 1 / x) [1 ..] main :: IO () main = do putStrLn "First 20 terms:" mapM_ putStrLn $ showRatio <$> take 20 harmonic putStrLn "\n100th term:" putStrLn $ showRatio (harmonic !! 99) putStrLn "" put...
Ensure the translated Haskell code behaves exactly like the original C++ snippet.
#include <fstream> #include <iostream> #include <locale> using namespace std; int main(void) { std::locale::global(std::locale("")); std::cout.imbue(std::locale()); ifstream in("input.txt"); wchar_t c; while ((c = in.get()) != in.eof()) wcout<<c; in.close(); return EXIT_...
#!/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...
Rewrite this program in Haskell while keeping its functionality equivalent to the C++ version.
#include "stdafx.h" #include <windows.h> #include <stdlib.h> const int BMP_WID = 410, BMP_HEI = 230, MAX_BALLS = 120; class myBitmap { public: myBitmap() : pen( NULL ), brush( NULL ), clr( 0 ), wid( 1 ) {} ~myBitmap() { DeleteObject( pen ); DeleteObject( brush ); DeleteDC( hdc ); DeleteObject(...
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 ...
Rewrite this program in Haskell while keeping its functionality equivalent to the C++ version.
#include <algorithm> #include <iostream> #include <vector> typedef unsigned long long integer; std::vector<integer> get_ancestors(const std::vector<integer>& ancestor, integer n) { std::vector<integer> result; for (integer a = ancestor[n]; a != 0 && a != n; ) { n = a; a = ancestor[n]; ...
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 ...
Change the following C++ code into Haskell without altering its purpose.
#include <iostream> void f(int n) { if (n < 1) { return; } int i = 1; while (true) { int sq = i * i; while (sq > n) { sq /= 10; } if (sq == n) { printf("%3d %9d %4d\n", n, i * i, i); return; } i++; } } int...
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...
Please provide an equivalent version of this C++ code in Haskell.
#include <iostream> void f(int n) { if (n < 1) { return; } int i = 1; while (true) { int sq = i * i; while (sq > n) { sq /= 10; } if (sq == n) { printf("%3d %9d %4d\n", n, i * i, i); return; } i++; } } int...
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 <iostream> int circlesort(int* arr, int lo, int hi, int swaps) { if(lo == hi) { return swaps; } int high = hi; int low = lo; int mid = (high - low) / 2; while(lo < hi) { if(arr[lo] > arr[hi]) { int temp = arr[lo]; arr[lo] = arr[hi]; a...
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...
Keep all operations the same but rewrite the snippet in Haskell.
#include <array> #include <iostream> #include <fstream> #include <map> #include <string> #include <vector> #include <boost/program_options.hpp> class letterset { public: letterset() { count_.fill(0); } explicit letterset(const std::string& str) { count_.fill(0); for (char c : str)...
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 ...
Generate a Haskell translation of this C++ snippet without changing its computational steps.
#include <iostream> #include <iterator> #include <string> #include <utility> #include <vector> namespace detail { template <typename ForwardIterator> class tokenizer { ForwardIterator _tbegin, _tend, _end; public: tokenizer(ForwardIterator begin, ForwardIterator end) : _tbegin(begin), _tend(begin), _end(end...
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)...
Rewrite the snippet below in Haskell so it works the same as the original C++ code.
#include <initializer_list> #include <iostream> #include <map> #include <vector> struct Wheel { private: std::vector<char> values; size_t index; public: Wheel() : index(0) { } Wheel(std::initializer_list<char> data) : values(data), index(0) { if (values.size() < 1) { ...
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 = ...
Can you help me rewrite this code in Haskell instead of C++, keeping it the same logically?
#include <initializer_list> #include <iostream> #include <map> #include <vector> struct Wheel { private: std::vector<char> values; size_t index; public: Wheel() : index(0) { } Wheel(std::initializer_list<char> data) : values(data), index(0) { if (values.size() < 1) { ...
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 = ...
Maintain the same structure and functionality when rewriting this code in Haskell.
#include <iostream> #include <cmath> #include <tuple> struct point { double x, y; }; bool operator==(const point& lhs, const point& rhs) { return std::tie(lhs.x, lhs.y) == std::tie(rhs.x, rhs.y); } enum result_category { NONE, ONE_COINCEDENT, ONE_DIAMETER, TWO, INFINITE }; using result_t = std::tuple<result_categor...
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...
Translate this program into Haskell but keep the logic exactly as in C++.
#include <iostream> #include <cmath> #include <tuple> struct point { double x, y; }; bool operator==(const point& lhs, const point& rhs) { return std::tie(lhs.x, lhs.y) == std::tie(rhs.x, rhs.y); } enum result_category { NONE, ONE_COINCEDENT, ONE_DIAMETER, TWO, INFINITE }; using result_t = std::tuple<result_categor...
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...
Keep all operations the same but rewrite the snippet in Haskell.
#include <vector> #include <utility> #include <algorithm> #include <iostream> #include <sstream> #include <string> #include <cmath> bool isVampireNumber( long number, std::vector<std::pair<long, long> > & solution ) { std::ostringstream numberstream ; numberstream << number ; std::string numberstring( number...
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...
Can you help me rewrite this code in Haskell instead of C++, keeping it the same logically?
#include <iostream> #include <sstream> #include <algorithm> #include <vector> using namespace std; class poker { public: poker() { face = "A23456789TJQK"; suit = "SHCD"; } string analyze( string h ) { memset( faceCnt, 0, 13 ); memset( suitCnt, 0, 4 ); vector<string> hand; transform( h.begin(), h.end(), ...
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...
Convert this C++ snippet to Haskell and keep its semantics consistent.
#include <iostream> #include <sstream> #include <algorithm> #include <vector> using namespace std; class poker { public: poker() { face = "A23456789TJQK"; suit = "SHCD"; } string analyze( string h ) { memset( faceCnt, 0, 13 ); memset( suitCnt, 0, 4 ); vector<string> hand; transform( h.begin(), h.end(), ...
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...
Preserve the algorithm and functionality while converting the code from C++ to Haskell.
#include <windows.h> #include <string> using namespace std; class myBitmap { public: myBitmap() : pen( NULL ) {} ~myBitmap() { DeleteObject( pen ); DeleteDC( hdc ); DeleteObject( bmp ); } bool create( int w, int h ) { BITMAPINFO bi; ZeroMemory( &bi, siz...
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...
Keep all operations the same but rewrite the snippet in Haskell.
#include <time.h> #include <iostream> #include <string> using namespace std; class penney { public: penney() { pW = cW = 0; } void gameLoop() { string a; while( true ) { playerChoice = computerChoice = ""; if( rand() % 2 ) { computer(); player(); } else { player(); comput...
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...
Translate the given C++ code snippet into Haskell without altering its behavior.
#include <windows.h> #include <string> #include <iostream> const int BMP_SIZE = 612; class myBitmap { public: myBitmap() : pen( NULL ), brush( NULL ), clr( 0 ), wid( 1 ) {} ~myBitmap() { DeleteObject( pen ); DeleteObject( brush ); DeleteDC( hdc ); DeleteObject( bmp ); } bool create( ...
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
Port the following code from C++ to Haskell with equivalent syntax and logic.
#include <windows.h> #include <string> #include <iostream> const int BMP_SIZE = 612; class myBitmap { public: myBitmap() : pen( NULL ), brush( NULL ), clr( 0 ), wid( 1 ) {} ~myBitmap() { DeleteObject( pen ); DeleteObject( brush ); DeleteDC( hdc ); DeleteObject( bmp ); } bool create( ...
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 a Haskell translation of this C++ snippet without changing its computational steps.
#include <iostream> struct Interval { int start, end; bool print; }; int main() { Interval intervals[] = { {2, 1000, true}, {1000, 4000, true}, {2, 10000, false}, {2, 100000, false}, {2, 1000000, false}, {2, 10000000, false}, {2, 100000000, false}, ...
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...
Can you help me rewrite this code in Haskell instead of C++, keeping it the same logically?
#include <iostream> struct Interval { int start, end; bool print; }; int main() { Interval intervals[] = { {2, 1000, true}, {1000, 4000, true}, {2, 10000, false}, {2, 100000, false}, {2, 1000000, false}, {2, 10000000, false}, {2, 100000000, false}, ...
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...
Change the programming language of this snippet from C++ to Haskell without modifying what it does.
#include <iostream> bool valid(int n, int nuts) { for (int k = n; k != 0; k--, nuts -= 1 + nuts / n) { if (nuts % n != 1) { return false; } } return nuts != 0 && (nuts % n == 0); } int main() { int x = 0; for (int n = 2; n < 10; n++) { while (!valid(n, x)) { ...
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...
Rewrite the snippet below in Haskell so it works the same as the original C++ code.
#include <iostream> bool valid(int n, int nuts) { for (int k = n; k != 0; k--, nuts -= 1 + nuts / n) { if (nuts % n != 1) { return false; } } return nuts != 0 && (nuts % n == 0); } int main() { int x = 0; for (int n = 2; n < 10; n++) { while (!valid(n, x)) { ...
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...