Instruction
stringlengths
45
106
input_code
stringlengths
1
13.7k
output_code
stringlengths
1
13.7k
Write the same algorithm in Haskell as shown in this C++ implementation.
#include <windows.h> #include <ctime> #include <string> #include <iostream> const int BMP_SIZE = 600; class myBitmap { public: myBitmap() : pen( NULL ), brush( NULL ), clr( 0 ), wid( 1 ) {} ~myBitmap() { DeleteObject( pen ); DeleteObject( brush ); DeleteDC( hdc ); DeleteObject( bmp ); } ...
import Control.Monad (replicateM) import Control.Monad.Random (fromList) type Point = (Float,Float) type Transformations = [(Point -> Point, Float)] gameOfChaos :: MonadRandom m => Int -> Transformations -> Point -> m [Point] gameOfChaos n transformations x = iterateA (fromList transformations) x where iterateA f...
Please provide an equivalent version of this C++ code in Haskell.
#include <ciso646> #include <iostream> #include <regex> #include <sstream> #include <string> #include <unordered_map> #include <utility> #include <vector> using std::vector; using std::string; #include <exception> #include <stdexcept> template <typename...Args> std::runtime_error error( Args...args ) { return st...
import Text.Printf prec :: String -> Int prec "^" = 4 prec "*" = 3 prec "/" = 3 prec "+" = 2 prec "-" = 2 leftAssoc :: String -> Bool leftAssoc "^" = False leftAssoc _ = True isOp :: String -> Bool isOp [t] = t `elem` "-+/*^" isOp _ = False simSYA :: [String] -> [([String], [String], String)] simSYA xs = final <> [...
Write a version of this C++ function in Haskell with identical behavior.
#include <list> #include <algorithm> #include <iostream> class point { public: point( int a = 0, int b = 0 ) { x = a; y = b; } bool operator ==( const point& o ) { return o.x == x && o.y == y; } point operator +( const point& o ) { return point( o.x + x, o.y + y ); } int x, y; }; class map { public: ...
module PQueue where data PQueue a = EmptyQueue | Node (Int, a) (PQueue a) (PQueue a) deriving (Show, Foldable) instance Ord a => Semigroup (PQueue a) where h1@(Node (w1, x1) l1 r1) <> h2@(Node (w2, x2) l2 r2) | w1 < w2 = Node (w1, x1) (h2 <> r1) l1 | otherwise = Node (w2, x2) (h1 <> r2) ...
Convert this C++ snippet to Haskell and keep its semantics consistent.
#include <list> #include <algorithm> #include <iostream> class point { public: point( int a = 0, int b = 0 ) { x = a; y = b; } bool operator ==( const point& o ) { return o.x == x && o.y == y; } point operator +( const point& o ) { return point( o.x + x, o.y + y ); } int x, y; }; class map { public: ...
module PQueue where data PQueue a = EmptyQueue | Node (Int, a) (PQueue a) (PQueue a) deriving (Show, Foldable) instance Ord a => Semigroup (PQueue a) where h1@(Node (w1, x1) l1 r1) <> h2@(Node (w2, x2) l2 r2) | w1 < w2 = Node (w1, x1) (h2 <> r1) l1 | otherwise = Node (w2, x2) (h1 <> r2) ...
Convert this C++ block to Haskell, preserving its control flow and logic.
template<uint _N, uint _G> class Nonogram { enum class ng_val : char {X='#',B='.',V='?'}; template<uint _NG> struct N { N() {} N(std::vector<int> ni,const int l) : X{},B{},Tx{},Tb{},ng(ni),En{},gNG(l){} std::bitset<_NG> X, B, T, Tx, Tb; std::vector<int> ng; int En, gNG; void fn (con...
import Control.Applicative ((<|>)) import Control.Monad import Control.Monad.CSP import Data.List (transpose) import System.Environment (getArgs) import Text.ParserCombinators.ReadP (ReadP) import qualified Text.ParserComb...
Change the following C++ code into Haskell without altering its purpose.
template<uint _N, uint _G> class Nonogram { enum class ng_val : char {X='#',B='.',V='?'}; template<uint _NG> struct N { N() {} N(std::vector<int> ni,const int l) : X{},B{},Tx{},Tb{},ng(ni),En{},gNG(l){} std::bitset<_NG> X, B, T, Tx, Tb; std::vector<int> ng; int En, gNG; void fn (con...
import Control.Applicative ((<|>)) import Control.Monad import Control.Monad.CSP import Data.List (transpose) import System.Environment (getArgs) import Text.ParserCombinators.ReadP (ReadP) import qualified Text.ParserComb...
Port the following code from C++ to Haskell with equivalent syntax and logic.
#include <boost/multiprecision/cpp_dec_float.hpp> #include <boost/multiprecision/gmp.hpp> #include <iomanip> #include <iostream> namespace mp = boost::multiprecision; using big_int = mp::mpz_int; using big_float = mp::cpp_dec_float_100; using rational = mp::mpq_rational; big_int factorial(int n) { big_int result ...
import Control.Monad import Data.Number.CReal import GHC.Integer import Text.Printf iterations = 52 main = do printf "N. %44s %4s %s\n" "Integral part of Nth term" "Γ—10^" "=Actual value of Nth term" forM_ [0..9] $ \n -> printf "%d. %44d %4d %s\n" n (almkvistGiulleraIn...
Transform the following C++ implementation into Haskell, maintaining the same output and logic.
#include <boost/multiprecision/cpp_dec_float.hpp> #include <boost/multiprecision/gmp.hpp> #include <iomanip> #include <iostream> namespace mp = boost::multiprecision; using big_int = mp::mpz_int; using big_float = mp::cpp_dec_float_100; using rational = mp::mpq_rational; big_int factorial(int n) { big_int result ...
import Control.Monad import Data.Number.CReal import GHC.Integer import Text.Printf iterations = 52 main = do printf "N. %44s %4s %s\n" "Integral part of Nth term" "Γ—10^" "=Actual value of Nth term" forM_ [0..9] $ \n -> printf "%d. %44d %4d %s\n" n (almkvistGiulleraIn...
Write the same code in Haskell as shown below in C++.
#include <iostream> #include <map> #include <vector> #include <gmpxx.h> using integer = mpz_class; integer reverse(integer n) { integer rev = 0; while (n > 0) { rev = rev * 10 + (n % 10); n /= 10; } return rev; } void print_vector(const std::vector<integer>& vec) { if (vec.empty()...
module Main where import Data.List procLychrel :: Integer -> [Integer] procLychrel a = a : pl a where pl n = let s = n + reverseInteger n in if isPalindrome s then [s] else s : pl s isPalindrome :: Integer -> Bool isPalindrome n = let s = show n in (...
Please provide an equivalent version of this C++ code in Haskell.
#include <iostream> #include <map> #include <vector> #include <gmpxx.h> using integer = mpz_class; integer reverse(integer n) { integer rev = 0; while (n > 0) { rev = rev * 10 + (n % 10); n /= 10; } return rev; } void print_vector(const std::vector<integer>& vec) { if (vec.empty()...
module Main where import Data.List procLychrel :: Integer -> [Integer] procLychrel a = a : pl a where pl n = let s = n + reverseInteger n in if isPalindrome s then [s] else s : pl s isPalindrome :: Integer -> Bool isPalindrome n = let s = show n in (...
Change the programming language of this snippet from C++ to Haskell without modifying what it does.
#include <iomanip> #include <iostream> #include <sstream> using namespace std; enum CipherMode {ENCRYPT, DECRYPT}; uint32_t randRsl[256]; uint32_t randCnt; uint32_t mm[256]; uint32_t aa = 0, bb = 0, cc = 0; void isaac() { ++cc; bb += cc; for (uint32_t i = 0; i < 256; ++i) { uin...
import Data.Array (Array, (!), (//), array, elems) import Data.Word (Word, Word32) import Data.Bits (shift, xor) import Data.Char (toUpper) import Data.List (unfoldr) import Numeric (showHex) type IArray = Array Word32 Word32 data IsaacState = IState { randrsl :: IArray , randcnt :: Word32 , mm :: IArray , aa...
Can you help me rewrite this code in Haskell instead of C++, keeping it the same logically?
#include <iomanip> #include <iostream> #include <sstream> using namespace std; enum CipherMode {ENCRYPT, DECRYPT}; uint32_t randRsl[256]; uint32_t randCnt; uint32_t mm[256]; uint32_t aa = 0, bb = 0, cc = 0; void isaac() { ++cc; bb += cc; for (uint32_t i = 0; i < 256; ++i) { uin...
import Data.Array (Array, (!), (//), array, elems) import Data.Word (Word, Word32) import Data.Bits (shift, xor) import Data.Char (toUpper) import Data.List (unfoldr) import Numeric (showHex) type IArray = Array Word32 Word32 data IsaacState = IState { randrsl :: IArray , randcnt :: Word32 , mm :: IArray , aa...
Rewrite this program in Haskell while keeping its functionality equivalent to the C++ version.
#include <string> #include <chrono> #include <cmath> #include <locale> using namespace std; using namespace chrono; unsigned int js(int l, int n) { unsigned int res = 0, f = 1; double lf = log(2) / log(10), ip; for (int i = l; i > 10; i /= 10) f *= 10; while (n > 0) if ((int)(f * pow(10, modf(++res * ...
import Control.Monad (guard) import Text.Printf (printf) p :: Int -> Int -> Int p l n = calc !! pred n where digitCount = floor $ logBase 10 (fromIntegral l :: Float) log10pwr = logBase 10 2 calc = do raised <- [-1 ..] let firstDigits = floor $ 10 ** (snd (properFracti...
Write the same code in Haskell as shown below in C++.
#include <string> #include <chrono> #include <cmath> #include <locale> using namespace std; using namespace chrono; unsigned int js(int l, int n) { unsigned int res = 0, f = 1; double lf = log(2) / log(10), ip; for (int i = l; i > 10; i /= 10) f *= 10; while (n > 0) if ((int)(f * pow(10, modf(++res * ...
import Control.Monad (guard) import Text.Printf (printf) p :: Int -> Int -> Int p l n = calc !! pred n where digitCount = floor $ logBase 10 (fromIntegral l :: Float) log10pwr = logBase 10 2 calc = do raised <- [-1 ..] let firstDigits = floor $ 10 ** (snd (properFracti...
Produce a language-to-language conversion: from C++ to Haskell, same semantics.
#include <algorithm> #include <iomanip> #include <iostream> #include <map> #include <gmpxx.h> using integer = mpz_class; class stirling2 { public: integer get(int n, int k); private: std::map<std::pair<int, int>, integer> cache_; }; integer stirling2::get(int n, int k) { if (k == n) return 1; ...
import Text.Printf (printf) import Data.List (groupBy) import qualified Data.MemoCombinators as Memo stirling2 :: Integral a => (a, a) -> a stirling2 = Memo.pair Memo.integral Memo.integral f where f (n, k) | n == 0 && k == 0 = 1 | (n > 0 && k == 0) || (n == 0 && k > 0) = 0 | n == k = 1 |...
Translate this program into Haskell but keep the logic exactly as in C++.
#include <algorithm> #include <iomanip> #include <iostream> #include <map> #include <gmpxx.h> using integer = mpz_class; class stirling2 { public: integer get(int n, int k); private: std::map<std::pair<int, int>, integer> cache_; }; integer stirling2::get(int n, int k) { if (k == n) return 1; ...
import Text.Printf (printf) import Data.List (groupBy) import qualified Data.MemoCombinators as Memo stirling2 :: Integral a => (a, a) -> a stirling2 = Memo.pair Memo.integral Memo.integral f where f (n, k) | n == 0 && k == 0 = 1 | (n > 0 && k == 0) || (n == 0 && k > 0) = 0 | n == k = 1 |...
Convert this C++ snippet to Haskell and keep its semantics consistent.
#include <cassert> #include <algorithm> #include <iomanip> #include <iostream> #include <vector> #include <gmpxx.h> using big_int = mpz_class; bool is_prime(const big_int& n) { return mpz_probab_prime_p(n.get_mpz_t(), 25); } template <typename integer> class n_smooth_generator { public: explicit n_smooth_gen...
import Control.Monad (guard) import Data.List (intercalate) import Data.List.Split (chunksOf) import Math.NumberTheory.Primes (Prime, unPrime, nextPrime) import Math.NumberTheory.Primes.Testing (isPrime) import Text.Printf (printf) data PierPointKind = First | Second merge :: Ord a => [a] -> [a] -> [a] merge [] b = b...
Ensure the translated Haskell code behaves exactly like the original C++ snippet.
#include <algorithm> #include <iostream> #include <vector> std::vector<uint64_t> primes; std::vector<uint64_t> smallPrimes; 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 <...
import Data.Numbers.Primes (primes) import Text.Printf (printf) merge :: Ord a => [a] -> [a] -> [a] merge [] b = b merge a@(x:xs) b@(y:ys) | x < y = x : merge xs b | otherwise = y : merge a ys nSmooth :: Integer -> [Integer] nSmooth p = 1 : foldr u [] factors where factors = takeWhi...
Convert the following code from C++ to Haskell, ensuring the logic remains intact.
#include <algorithm> #include <functional> #include <iostream> #include <vector> std::vector<int> primes; struct Seq { public: bool empty() { return p < 0; } int front() { return p; } void popFront() { if (p == 2) { p++; } else { p += 2; ...
import Data.List (delete, intercalate) import Data.Numbers.Primes (primes) import Data.Bool (bool) partitions :: Int -> Int -> [Int] partitions x n | n <= 1 = [ x | x == last ps ] | otherwise = go ps x n where ps = takeWhile (<= x) primes go ps_ x 1 = [ x | x `elem` ps_ ] go ps_ ...
Rewrite the snippet below in Haskell so it works the same as the original C++ code.
#include <iostream> enum class zd {N00,N01,N10,N11}; class N { private: int dVal = 0, dLen; void _a(int i) { for (;; i++) { if (dLen < i) dLen = i; switch ((zd)((dVal >> (i*2)) & 3)) { case zd::N00: case zd::N01: return; case zd::N10: if (((dVal >> ((i+1)*2)) & 1) != 1) return;...
import Data.List (find, mapAccumL) import Control.Arrow (first, second) fibs :: Num a => a -> a -> [a] fibs a b = res where res = a : b : zipWith (+) res (tail res) data Fib = Fib { sign :: Int, digits :: [Int]} mkFib s ds = case dropWhile (==0) ds of [] -> 0 ds -> Fib s (reverse ds) instance S...
Generate an equivalent Haskell version of this C++ code.
#include <algorithm> #include <iomanip> #include <iostream> #include <map> #include <gmpxx.h> using integer = mpz_class; class unsigned_stirling1 { public: integer get(int n, int k); private: std::map<std::pair<int, int>, integer> cache_; }; integer unsigned_stirling1::get(int n, int k) { if (k == 0) ...
import Text.Printf (printf) import Data.List (groupBy) import qualified Data.MemoCombinators as Memo stirling1 :: Integral a => (a, a) -> a stirling1 = Memo.pair Memo.integral Memo.integral f where f (n, k) | n == 0 && k == 0 = 1 | n > 0 && k == 0 = 0 | k > n = 0 | otherwise =...
Maintain the same structure and functionality when rewriting this code in Haskell.
#include <algorithm> #include <iomanip> #include <iostream> #include <map> #include <gmpxx.h> using integer = mpz_class; class unsigned_stirling1 { public: integer get(int n, int k); private: std::map<std::pair<int, int>, integer> cache_; }; integer unsigned_stirling1::get(int n, int k) { if (k == 0) ...
import Text.Printf (printf) import Data.List (groupBy) import qualified Data.MemoCombinators as Memo stirling1 :: Integral a => (a, a) -> a stirling1 = Memo.pair Memo.integral Memo.integral f where f (n, k) | n == 0 && k == 0 = 1 | n > 0 && k == 0 = 0 | k > n = 0 | otherwise =...
Rewrite this program in Haskell while keeping its functionality equivalent to the C++ version.
#include <iostream> #include <cmath> #include <cassert> using namespace std; #define PI 3.14159265359 class Vector { public: Vector(double ix, double iy, char mode) { if(mode=='a') { x=ix*cos(iy); y=ix*sin(iy); } else { x=ix; ...
add (u,v) (x,y) = (u+x,v+y) minus (u,v) (x,y) = (u-x,v-y) multByScalar k (x,y) = (k*x,k*y) divByScalar (x,y) k = (x/k,y/k) main = do let vecA = (3.0,8.0) let (r,theta) = (3,pi/12) :: (Double,Double) let vecB = (r*(cos theta),r*(sin theta)) putStrLn $ "vecA = " ++ (show vecA) putStrLn $ "vecB = " +...
Produce a functionally identical Haskell code for the snippet given in C++.
#include <cmath> #include <iostream> using namespace std; class EllipticPoint { double m_x, m_y; static constexpr double ZeroThreshold = 1e20; static constexpr double B = 7; void Double() noexcept { if(IsZero()) { ...
import Data.Monoid import Control.Monad (guard) import Test.QuickCheck (quickCheck)
Convert this C++ snippet to Haskell and keep its semantics consistent.
#include <cmath> #include <iostream> using namespace std; class EllipticPoint { double m_x, m_y; static constexpr double ZeroThreshold = 1e20; static constexpr double B = 7; void Double() noexcept { if(IsZero()) { ...
import Data.Monoid import Control.Monad (guard) import Test.QuickCheck (quickCheck)
Translate this program into Haskell but keep the logic exactly as in C++.
#include <algorithm> #include <iostream> #include <vector> const int STX = 0x02; const int ETX = 0x03; void rotate(std::string &a) { char t = a[a.length() - 1]; for (int i = a.length() - 1; i > 0; i--) { a[i] = a[i - 1]; } a[0] = t; } std::string bwt(const std::string &s) { for (char c : ...
import Data.List ((!!), find, sort, tails, transpose) import Data.Maybe (fromJust) import Text.Printf (printf) newtype BWT a = BWT [Val a] bwt :: Ord a => [a] -> BWT a bwt xs = let n = length xs + 2 ys = transpose $ sort $ take n $ tails $ cycle $ pos xs in BWT $ ys !! (n-1) invBwt :: Or...
Maintain the same structure and functionality when rewriting this code in Haskell.
#include <algorithm> #include <iostream> #include <vector> const int STX = 0x02; const int ETX = 0x03; void rotate(std::string &a) { char t = a[a.length() - 1]; for (int i = a.length() - 1; i > 0; i--) { a[i] = a[i - 1]; } a[0] = t; } std::string bwt(const std::string &s) { for (char c : ...
import Data.List ((!!), find, sort, tails, transpose) import Data.Maybe (fromJust) import Text.Printf (printf) newtype BWT a = BWT [Val a] bwt :: Ord a => [a] -> BWT a bwt xs = let n = length xs + 2 ys = transpose $ sort $ take n $ tails $ cycle $ pos xs in BWT $ ys !! (n-1) invBwt :: Or...
Please provide an equivalent version of this C++ code in Haskell.
#include <exception> #include <iomanip> #include <iostream> #include <numeric> #include <sstream> #include <vector> class Frac { public: Frac() : num(0), denom(1) {} Frac(int n, int d) { if (d == 0) { throw std::runtime_error("d must not be zero"); } int sign_of_d = d < 0 ? -1 : 1; int g = std::gcd(n,...
import Data.Ratio (Ratio, denominator, numerator, (%)) faulhaber :: Int -> Rational -> Rational faulhaber p n = sum $ zipWith ((*) . (n ^)) [1 ..] (faulhaberTriangle !! p) faulhaberTriangle :: [[Rational]] faulhaberTriangle = tail $ scanl ( \rs n -> let xs = zipWith ((*) . (n %)) [2 ..]...
Rewrite the snippet below in Haskell so it works the same as the original C++ code.
#include <iostream> #include <numeric> #include <sstream> #include <vector> class Frac { public: Frac(long n, long d) { if (d == 0) { throw new std::runtime_error("d must not be zero"); } long nn = n; long dd = d; if (nn == 0) { dd = 1; } else if (dd < 0) { nn = -nn; dd = -dd; } long g =...
import Data.Ratio ((%), numerator, denominator) import Data.List (intercalate, transpose) import Data.Bifunctor (bimap) import Data.Char (isSpace) import Data.Monoid ((<>)) import Data.Bool (bool) faulhaber :: [[Rational]] faulhaber = tail $ scanl (\rs n -> let xs = zipWith ((*) . (n %)) [2 ..] rs ...
Preserve the algorithm and functionality while converting the code from C++ to Haskell.
#include <vector> #include <iostream> #include <cmath> #include <utility> #include <map> #include <iomanip> bool isPrime( int i ) { int stop = std::sqrt( static_cast<double>( i ) ) ; for ( int d = 2 ; d <= stop ; d++ ) if ( i % d == 0 ) return false ; return true ; } class Compare { public : Compa...
import Data.List (group, sort) import Text.Printf (printf) import Data.Numbers.Primes (primes) freq :: [(Int, Int)] -> Float freq xs = realToFrac (length xs) / 100 line :: [(Int, Int)] -> IO () line t@((n1, n2):xs) = printf "%d -> %d count: %5d frequency: %2.2fΒ %%\n" n1 n2 (length t) (freq t) main :: IO () main = m...
Write the same code in Haskell as shown below in C++.
#include <iostream> #include <vector> std::vector<long> TREE_LIST; std::vector<int> OFFSET; void init() { for (size_t i = 0; i < 32; i++) { if (i == 1) { OFFSET.push_back(1); } else { OFFSET.push_back(0); } } } void append(long t) { TREE_LIST.push_back(1 | ...
parts :: Int -> [[(Int, Int)]] parts n = f n 1 where f n x | n == 0 = [[]] | x > n = [] | otherwise = f n (x + 1) ++ concatMap (\c -> map ((c, x) :) (f (n - c * x) (x + 1))) [1 .. n `div` x] pick :: Int -> [String] -> [String] pick _ [] = [] pick 0 _ = [""]...
Translate this program into Haskell but keep the logic exactly as in C++.
#include <bitset> #include <stdio.h> #define SIZE 80 #define RULE 30 #define RULE_TEST(x) (RULE & 1 << (7 & (x))) void evolve(std::bitset<SIZE> &s) { int i; std::bitset<SIZE> t(0); t[SIZE-1] = RULE_TEST( s[0] << 2 | s[SIZE-1] << 1 | s[SIZE-2] ); t[ 0] = RULE_TEST( s[...
import CellularAutomata (fromList, rule, runCA) import Control.Comonad import Data.List (unfoldr) rnd = fromBits <$> unfoldr (pure . splitAt 8) bits where size = 80 bits = extract <$> runCA (rule 30) (fromList (1 : replicate size 0)) fromBits = foldl ((+) . (2 *)) 0
Translate the given C++ code snippet into Haskell without altering its behavior.
#include <algorithm> #include <iostream> #include <iterator> #include <vector> const int luckySize = 60000; std::vector<int> luckyEven(luckySize); std::vector<int> luckyOdd(luckySize); void init() { for (int i = 0; i < luckySize; ++i) { luckyEven[i] = i * 2 + 2; luckyOdd[i] = i * 2 + 1; } } v...
import System.Environment import Text.Regex.Posix data Lucky = Lucky | EvenLucky helpMessage :: IO () helpMessage = do putStrLn " what is displayed (on a single line)" putStrLn " argument(s) (optional verbiage is encouraged)" putStrLn "======================|========...
Change the following C++ code into Haskell without altering its purpose.
#include <algorithm> #include <complex> #include <iomanip> #include <iostream> std::complex<double> inv(const std::complex<double>& c) { double denom = c.real() * c.real() + c.imag() * c.imag(); return std::complex<double>(c.real() / denom, -c.imag() / denom); } class QuaterImaginary { public: QuaterImagi...
import Data.Char (chr, digitToInt, intToDigit, isDigit, ord) import Data.Complex (Complex (..), imagPart, realPart) import Data.List (delete, elemIndex) import Data.Maybe (fromMaybe) base :: Complex Float base = 0 :+ 2 quotRemPositive :: Int -> Int -> (Int, Int) quotRemPositive a b | r < 0 = (1 + q, floor (realPart...
Change the following C++ code into Haskell without altering its purpose.
#include <random> #include <map> #include <string> #include <iostream> #include <cmath> #include <iomanip> int main( ) { std::random_device myseed ; std::mt19937 engine ( myseed( ) ) ; std::normal_distribution<> normDistri ( 2 , 3 ) ; std::map<int , int> normalFreq ; int sum = 0 ; double mean = 0.0 ...
import Data.Map (Map, empty, insert, findWithDefault, toList) import Data.Maybe (fromMaybe) import Text.Printf (printf) import Data.Function (on) import Data.List (sort, maximumBy, minimumBy) import Control.Monad.Random (RandomGen, Rand, evalRandIO, getRandomR) import Control.Monad (replicateM) getNorm :: RandomGen g...
Change the programming language of this snippet from C++ to Haskell without modifying what it does.
#include <iostream> #include <vector> __int128 imax(__int128 a, __int128 b) { if (a > b) { return a; } return b; } __int128 ipow(__int128 b, __int128 n) { if (n == 0) { return 1; } if (n == 1) { return b; } __int128 res = b; while (n > 1) { res *= b...
import Data.Bifunctor (bimap) import Data.List (find) import Data.Maybe (isJust) b10 :: Integral a => a -> Integer b10 n = read (digitMatch rems sums) :: Integer where (_, rems, _, Just (_, sums)) = until (\(_, _, _, mb) -> isJust mb) ( \(e, rems, ms, _) -> let m = rem (10 ^ e...
Port the following code from C++ to Haskell with equivalent syntax and logic.
#include <iostream> #include <sstream> #include <iomanip> using namespace std; class magicSqr { public: magicSqr() { sqr = 0; } ~magicSqr() { if( sqr ) delete [] sqr; } void create( int d ) { if( sqr ) delete [] sqr; if( d & 1 ) d++; while( d % 4 == 0 ) { d += 2; } sz = ...
import qualified Data.Map.Strict as M import Data.List (transpose, intercalate) import Data.Maybe (fromJust, isJust) import Control.Monad (forM_) import Data.Monoid ((<>)) magic :: Int -> [[Int]] magic n = mapAsTable ((4 * n) + 2) (hiResMap n) hiResMap :: Int -> M.Map (Int, Int) Int hiResMap n = let mapLux = luxMa...
Produce a language-to-language conversion: from C++ to Haskell, same semantics.
#include <algorithm> #include <iostream> #include <numeric> #include <vector> std::vector<int> divisors(int n) { std::vector<int> divs = { 1 }; std::vector<int> divs2; for (int i = 2; i * i <= n; i++) { if (n % i == 0) { int j = n / i; divs.push_back(i); if (i !...
weirds :: [Int] weirds = filter abundantNotSemiperfect [1 ..] abundantNotSemiperfect :: Int -> Bool abundantNotSemiperfect n = let ds = descProperDivisors n d = sum ds - n in 0 < d && not (hasSum d ds) hasSum :: Int -> [Int] -> Bool hasSum _ [] = False hasSum n (x:xs) | n < x = hasSum n xs | otherwise =...
Convert this C++ snippet to Haskell and keep its semantics consistent.
#include <array> #include <bitset> #include <iostream> using namespace std; struct FieldDetails {string_view Name; int NumBits;}; template <const char *T> consteval auto ParseDiagram() { constexpr string_view rawArt(T); constexpr auto firstBar = rawArt.find("|"); constexpr auto lastBar = rawArt....
import Text.ParserCombinators.ReadP import Control.Monad (guard) data Field a = Field { fieldName :: String , fieldSize :: Int , fieldValue :: Maybe a} instance Show a => Show (Field a) where show (Field n s a) = case a of Nothing -> n ++ "\t" ++ show s Just x -> n ...
Generate a Haskell translation of this C++ snippet without changing its computational steps.
#include <iostream> #include <vector> std::vector<int> smallPrimes; bool is_prime(size_t test) { if (test < 2) { return false; } if (test % 2 == 0) { return test == 2; } for (size_t d = 3; d * d <= test; d += 2) { if (test % d == 0) { return false; } ...
import Control.Monad (guard) import Math.NumberTheory.ArithmeticFunctions (divisorCount) import Math.NumberTheory.Primes (Prime, unPrime) import Math.NumberTheory.Primes.Testing (isPrime) calc :: Integer -> [(Integer, Integer)] calc n = ...
Write the same algorithm in Haskell as shown in this C++ implementation.
#include <iostream> #include <tuple> #include <vector> std::pair<int, int> tryPerm(int, int, const std::vector<int>&, int, int); std::pair<int, int> checkSeq(int pos, const std::vector<int>& seq, int n, int minLen) { if (pos > minLen || seq[0] > n) return { minLen, 0 }; else if (seq[0] == n) return ...
import Data.List (union) total [] = [] total (x:xs) = brauer (x:xs) `union` total xs brauer [] = [] brauer (x:xs) = map (+ x) (x:xs) chains _ 1 = [[1]] chains sums n = go [[1]] where go ch = let next = ch >>= step complete = filter ((== n) . head) next in if null complete then go ...
Ensure the translated Haskell code behaves exactly like the original C++ snippet.
#include <iostream> #include <string> #include <vector> #include <queue> #include <regex> #include <tuple> #include <set> #include <array> using namespace std; class Board { public: vector<vector<char>> sData, dData; int px, py; Board(string b) { regex pattern("([^\\n]+)\\n?"); sregex_iterator end, it...
import Control.Monad (liftM) import Data.Array import Data.List (transpose) import Data.Maybe (mapMaybe) import qualified Data.Sequence as Seq import qualified Data.Set as Set import Prelude hiding (Left, Right) data Field = Space | Wall | Goal deriving (Eq) data Action = Up | Down | Left | Right | PushUp ...
Rewrite this program in Haskell while keeping its functionality equivalent to the C++ version.
#include <iostream"> #include <cmath> #include <vector> #include <algorithm> #include <iomanip> #include <numeric> using namespace std; const uint* binary(uint n, uint length); uint sum_subset_unrank_bin(const vector<uint>& d, uint r); vector<uint> factors(uint x); bool isPrime(uint number); bool isZum(uint n)...
import Data.List (group, sort) import Data.List.Split (chunksOf) import Data.Numbers.Primes (primeFactors) isZumkeller :: Int -> Bool isZumkeller n = let ds = divisors n m = sum ds in ( even m && let half = div m 2 in elem half ds || ( all (half >=) ds ...
Produce a functionally identical Haskell code for the snippet given in C++.
#include <algorithm> #include <functional> #include <iostream> #include <numeric> #include <vector> typedef std::vector<std::vector<int>> matrix; matrix dList(int n, int start) { start--; std::vector<int> a(n); std::iota(a.begin(), a.end(), 0); a[start] = a[0]; a[0] = start; std::sort(a.begi...
import Data.List (permutations, (\\)) import Control.Monad (foldM, forM_) latinSquares :: Eq a => [a] -> [[[a]]] latinSquares [] = [] latinSquares set = map reverse <$> squares where squares = foldM addRow firstRow perm perm = tail (groupedPermutations set) firstRow = pure <$> set addRow tbl rows = [...
Change the following C++ code into Haskell without altering its purpose.
#include <iostream> #include <string> using namespace std; class playfair { public: void doIt( string k, string t, bool ij, bool e ) { createGrid( k, ij ); getTextReady( t, ij, e ); if( e ) doIt( 1 ); else doIt( -1 ); display(); } private: void doIt( int dir ) { int a, b, c, d; string ntxt; ...
import Control.Monad (guard) import Data.Array (Array, assocs, elems, listArray, (!)) import Data.Char (toUpper) import Data.List (nub, (\\)) import Data.List.Split (chunksOf) import Data.Maybe (listToMaybe) import Data.String.Utils (replace) type Square a = Array (Int, Int) a arr...
Ensure the translated Haskell code behaves exactly like the original C++ snippet.
#include <iostream> #include <string> using namespace std; class playfair { public: void doIt( string k, string t, bool ij, bool e ) { createGrid( k, ij ); getTextReady( t, ij, e ); if( e ) doIt( 1 ); else doIt( -1 ); display(); } private: void doIt( int dir ) { int a, b, c, d; string ntxt; ...
import Control.Monad (guard) import Data.Array (Array, assocs, elems, listArray, (!)) import Data.Char (toUpper) import Data.List (nub, (\\)) import Data.List.Split (chunksOf) import Data.Maybe (listToMaybe) import Data.String.Utils (replace) type Square a = Array (Int, Int) a arr...
Transform the following C++ implementation into Haskell, maintaining the same output and logic.
#include <iostream> #include <iomanip> #include <string> class oo { public: void evolve( int l, int rule ) { std::string cells = "O"; std::cout << " Rule #" << rule << ":\n"; for( int x = 0; x < l; x++ ) { addNoCells( cells ); std::cout << std::setw( 40 + ( static...
import Control.Comonad import Data.InfList (InfList (..), (+++)) import qualified Data.InfList as Inf data Cells a = Cells (InfList a) a (InfList a) deriving Functor view n (Cells l x r) = reverse (Inf.take n l) ++ [x] ++ (Inf.take n r) fromList [] = fromList [0] fromList (x:xs) = let zeros = Inf.repeat 0 ...
Port the provided C++ code into Haskell while preserving the original functionality.
#include <algorithm> #include <iostream> #include <optional> #include <set> #include <string> #include <string_view> #include <vector> struct string_comparator { using is_transparent = void; bool operator()(const std::string& lhs, const std::string& rhs) const { return lhs < rhs; } bool operato...
import Data.List (isPrefixOf, intercalate) import Data.Tree (Tree(..)) wordBreaks :: [String] -> String -> String wordBreaks ws = (++) <*> (":\n" ++) . report . fmap go . tokenTrees ws where go t | null (subForest t) = [rootLabel t] | otherwise = subForest t >>= ((:) (rootLabel t) . go) report xs...
Translate the given C++ code snippet into Haskell without altering its behavior.
#include <cstdlib> #include <fstream> #include <iomanip> #include <iostream> #include <sstream> #include <vector> #include <openssl/sha.h> class sha256_exception : public std::exception { public: const char* what() const noexcept override { return "SHA-256 error"; } }; class sha256 { public: sha25...
import Control.Monad (mfilter) import Crypto.Hash.SHA256 (hash) import qualified Data.ByteString as B import Data.ByteString.Builder (byteStringHex, char7, hPutBuilder) import Data.Functor ((<&>)) import Data.Maybe (listToMaybe) import Data.Strict.Tuple (Pair(..)) import qualified Data.Strict.Tuple as T import System...
Preserve the algorithm and functionality while converting the code from C++ to Haskell.
#include <chrono> #include <iostream> #include <vector> #include <gmpxx.h> using big_int = mpz_class; big_int partitions(int n) { std::vector<big_int> p(n + 1); p[0] = 1; for (int i = 1; i <= n; ++i) { for (int k = 1;; ++k) { int j = (k * (3*k - 1))/2; if (j > i) ...
data Memo a = Node a (Memo a) (Memo a) deriving (Functor) memo :: Integral a => Memo p -> a -> p memo (Node a l r) n | n == 0 = a | odd n = memo l (n `div` 2) | otherwise = memo r (n `div` 2 - 1) nats :: Memo Int nats = Node 0 ((+ 1) . (* 2) <$> nats) ((* 2) . (+ 1) <$> nats) partitions...
Transform the following C++ implementation into Haskell, maintaining the same output and logic.
#include <iostream> #include <vector> #include <string> #include <cmath> std::string frmtPolynomial(std::vector<int> polynomial, bool remainder = false) { std::string r = ""; if (remainder) { r = " r: " + std::to_string(polynomial.back()); polynomial.pop_back(); } std::string formatted = ""; int deg...
import Data.List normalized :: (Eq a, Num a) => [a] -> [a] normalized = dropWhile (== 0) isZero :: (Eq a, Num a) => [a] -> Bool isZero = null . normalized shortDiv :: (Eq a, Fractional a) => [a] -> [a] -> ([a], [a]) shortDiv p1 p2 | isZero p2 = error "zero divisor" | otherwise = let go 0 p = p g...
Convert the following code from C++ to Haskell, ensuring the logic remains intact.
#include <iostream> #include <vector> #include <string> #include <cmath> std::string frmtPolynomial(std::vector<int> polynomial, bool remainder = false) { std::string r = ""; if (remainder) { r = " r: " + std::to_string(polynomial.back()); polynomial.pop_back(); } std::string formatted = ""; int deg...
import Data.List normalized :: (Eq a, Num a) => [a] -> [a] normalized = dropWhile (== 0) isZero :: (Eq a, Num a) => [a] -> Bool isZero = null . normalized shortDiv :: (Eq a, Fractional a) => [a] -> [a] -> ([a], [a]) shortDiv p1 p2 | isZero p2 = error "zero divisor" | otherwise = let go 0 p = p g...
Port the following code from C++ to Haskell with equivalent syntax and logic.
#include<iostream> #include<string> #include<boost/filesystem.hpp> #include<boost/format.hpp> #include<boost/iostreams/device/mapped_file.hpp> #include<optional> #include<algorithm> #include<iterator> #include<execution> #include"dependencies/xxhash.hpp" template<typename T, typename V, typename F> size_t for_each_...
import Crypto.Hash.MD5 (hash) import Data.ByteString as BS (readFile, ByteString()) import System.Environment (getArgs, getProgName) import System.Directory (doesDirectoryExist, getDirectoryContents) import System.FilePath.Posix ((</>)) import Control.Monad (forM) import Text.Printf ...
Port the provided C++ code into Haskell while preserving the original functionality.
#include <cmath> #include <iostream> #include <vector> std::vector<int> generate_primes(int limit) { std::vector<bool> sieve(limit >> 1, true); for (int p = 3, s = 9; s < limit; p += 2) { if (sieve[p >> 1]) { for (int q = s; q < limit; q += p << 1) sieve[q >> 1] = false; ...
import Data.Time.Clock.POSIX ( getPOSIXTime ) import Data.Int ( Int64 ) import Data.Bits ( Bits( shiftL, shiftR ) ) data Memo a = EmptyNode | Node a (Memo a) (Memo a) deriving Functor memo :: Integral a => Memo p -> a -> p memo (Node a l r) n | n == 0 = a | odd n = memo l (n `div` 2) | otherwise = memo r...
Change the programming language of this snippet from C++ to Haskell without modifying what it does.
#include <iostream> #include <cstdint> typedef uint64_t integer; integer reverse(integer n) { integer rev = 0; while (n > 0) { rev = rev * 10 + (n % 10); n /= 10; } return rev; } class palindrome_generator { public: palindrome_generator(int digit) : power_(10), next_(digit * pow...
import Control.Monad (guard) palindromic :: Int -> Bool palindromic n = d == reverse d where d = show n gapful :: Int -> Bool gapful n = n `rem` firstLastDigit == 0 where firstLastDigit = read [head asDigits, last asDigits] asDigits = show n result :: Int -> [Int] result d = do x <- [(d+100),(d+110)..] ...
Please provide an equivalent version of this C++ code in Haskell.
#include <iostream> #include <cstdint> typedef uint64_t integer; integer reverse(integer n) { integer rev = 0; while (n > 0) { rev = rev * 10 + (n % 10); n /= 10; } return rev; } class palindrome_generator { public: palindrome_generator(int digit) : power_(10), next_(digit * pow...
import Control.Monad (guard) palindromic :: Int -> Bool palindromic n = d == reverse d where d = show n gapful :: Int -> Bool gapful n = n `rem` firstLastDigit == 0 where firstLastDigit = read [head asDigits, last asDigits] asDigits = show n result :: Int -> [Int] result d = do x <- [(d+100),(d+110)..] ...
Convert this C++ snippet to Haskell and keep its semantics consistent.
#include <cstdint> #include <iostream> #include <vector> #include <primesieve.hpp> void print_diffs(const std::vector<uint64_t>& vec) { for (size_t i = 0, n = vec.size(); i != n; ++i) { if (i != 0) std::cout << " (" << vec[i] - vec[i - 1] << ") "; std::cout << vec[i]; } std::cou...
import Data.Numbers.Primes (primes) consecutives equiv = filter ((> 1) . length) . go [] where go r [] = [r] go [] (h : t) = go [h] t go (y : ys) (h : t) | y `equiv` h = go (h : y : ys) t | otherwise = (y : ys) : go [h] t maximumBy g (h : t) = foldr f h t where f r x = if g r < g x t...
Ensure the translated Haskell code behaves exactly like the original C++ snippet.
#include <iomanip> #include <iostream> #include <sstream> #include <utility> #include <primesieve.hpp> uint64_t digit_sum(uint64_t n) { uint64_t sum = 0; for (; n > 0; n /= 10) sum += n % 10; return sum; } class honaker_prime_generator { public: std::pair<uint64_t, uint64_t> next(); private:...
import Control.Monad (join) import Data.Bifunctor (bimap) import Data.List.Split (chunksOf) import Data.Numbers.Primes (primes) honakers :: [(Integer, Integer)] honakers = filter (uncurry (==) . both sumDigits) (zip [1 ..] primes) main :: IO () main = putStrLn "First Fifty:\n" >> mapM_ (putSt...
Convert the following code from C++ to Haskell, ensuring the logic remains intact.
#include <array> #include <iostream> #include <primesieve.hpp> class ormiston_triple_generator { public: ormiston_triple_generator() { for (int i = 0; i < 2; ++i) { primes_[i] = pi_.next_prime(); digits_[i] = get_digits(primes_[i]); } } std::array<uint64_t, 3> next_...
import Data.Numbers.Primes (primes) import Data.List (sort) ormistons :: [(Integer, Integer, Integer)] ormistons = concat $ zipWith3 (\(dx, x) (dy, y) (dz, z) -> [(x, y, z) | dx == dy && dx == dz]) primeDigits (tail primeDigits) (drop 2 primeDigits) primeDigits :: [(Integer, I...
Preserve the algorithm and functionality while converting the code from C++ to Haskell.
#include <iomanip> #include <iostream> #include <gmpxx.h> using big_int = mpz_class; class riordan_number_generator { public: big_int next(); private: big_int a0_ = 1; big_int a1_ = 0; int n_ = 0; }; big_int riordan_number_generator::next() { int n = n_++; if (n == 0) return a0_; ...
riordans :: [Integer] riordans = 1 : 0 : zipWith div ( zipWith (*) [1 ..] ( zipWith (+) ((2 *) <$> tail riordans) ((3 *) <$> riordans) ) ) [3 ..] main :: IO () main = putStrLn "First 32 Riordan terms:" >> mapM_ print (ta...
Generate an equivalent Haskell version of this C++ code.
#include <iomanip> #include <iostream> #include <gmpxx.h> using big_int = mpz_class; class riordan_number_generator { public: big_int next(); private: big_int a0_ = 1; big_int a1_ = 0; int n_ = 0; }; big_int riordan_number_generator::next() { int n = n_++; if (n == 0) return a0_; ...
riordans :: [Integer] riordans = 1 : 0 : zipWith div ( zipWith (*) [1 ..] ( zipWith (+) ((2 *) <$> tail riordans) ((3 *) <$> riordans) ) ) [3 ..] main :: IO () main = putStrLn "First 32 Riordan terms:" >> mapM_ print (ta...
Produce a functionally identical Haskell code for the snippet given in C++.
#include <cmath> #include <iostream> #include <string> using namespace std; struct LoggingMonad { double Value; string Log; }; auto operator>>(const LoggingMonad& monad, auto f) { auto result = f(monad.Value); return LoggingMonad{result.Value, monad.Log + "\n" + result.Log}; } auto Root = [](doub...
import Control.Monad.Trans.Writer import Control.Monad ((>=>)) loggingVersion :: (a -> b) -> c -> a -> Writer c b loggingVersion f log x = writer (f x, log) logRoot = loggingVersion sqrt "obtained square root, " logAddOne = loggingVersion (+1) "added 1, " logHalf = loggingVersion (/2) "divided by 2, " halfOfAddOneOf...
Maintain the same structure and functionality when rewriting this code in Haskell.
#include <algorithm> #include <fstream> #include <iostream> #include <map> #include <string> #include <vector> using word_map = std::map<size_t, std::vector<std::string>>; bool one_away(const std::string& s1, const std::string& s2) { if (s1.size() != s2.size()) return false; bool result = false; ...
import System.IO (readFile) import Control.Monad (foldM) import Data.List (intercalate) import qualified Data.Set as S distance :: String -> String -> Int distance s1 s2 = length $ filter not $ zipWith (==) s1 s2 wordLadders :: [String] -> String -> String -> [[String]] wordLadders dict start end | length start /= ...
Port the following code from C++ to Haskell with equivalent syntax and logic.
#include <iostream> #include <cstdint> struct Date { std::uint16_t year; std::uint8_t month; std::uint8_t day; }; constexpr bool leap(int year) { return year%4==0 && (year%100!=0 || year%400==0); } const std::string& weekday(const Date& date) { static const std::uint8_t leapdoom[] = {4,1,7,2,4,6...
import Text.Printf data Date = Date {year :: Int, month :: Int, day :: Int} instance Show Date where show Date {year = y, month = m, day = d} = printf "%4d-%02d-%02d" y m d leap :: Int -> Bool leap year = year `mod` 4 == 0 && (year `mod` 100 /= 0 || year `mod` 400 == 0) weekday :: Date -> Int weekday Da...
Ensure the translated Haskell code behaves exactly like the original C++ snippet.
#include <iostream> #include <cstdint> struct Date { std::uint16_t year; std::uint8_t month; std::uint8_t day; }; constexpr bool leap(int year) { return year%4==0 && (year%100!=0 || year%400==0); } const std::string& weekday(const Date& date) { static const std::uint8_t leapdoom[] = {4,1,7,2,4,6...
import Text.Printf data Date = Date {year :: Int, month :: Int, day :: Int} instance Show Date where show Date {year = y, month = m, day = d} = printf "%4d-%02d-%02d" y m d leap :: Int -> Bool leap year = year `mod` 4 == 0 && (year `mod` 100 /= 0 || year `mod` 400 == 0) weekday :: Date -> Int weekday Da...
Rewrite this program in Haskell while keeping its functionality equivalent to the C++ version.
#include <algorithm> #include <cassert> #include <iomanip> #include <iostream> #include <vector> template <typename scalar_type> class matrix { public: matrix(size_t rows, size_t columns) : rows_(rows), columns_(columns), elements_(rows * columns) {} matrix(size_t rows, size_t columns, scalar_type val...
isMatrix xs = null xs || all ((== (length.head $ xs)).length) xs isSquareMatrix xs = null xs || all ((== (length xs)).length) xs mult:: Num a => [[a]] -> [[a]] -> [[a]] mult uss vss = map ((\xs -> if null xs then [] else foldl1 (zipWith (+)) xs). zipWith (\vs u -> map (u*) vs) vss) uss matI::(Num a) => Int -> [[a]] ...
Translate this program into Haskell but keep the logic exactly as in C++.
#include <ctime> #include <iostream> #include <string> #include <algorithm> class chessBoard { public: void generateRNDBoard( int brds ) { int a, b, i; char c; for( int cc = 0; cc < brds; cc++ ) { memset( brd, 0, 64 ); std::string pieces = "PPPPPPPPNNBBRRQKppppppppnnbbrrqk";...
module RandomChess ( placeKings , placePawns , placeRemaining , emptyBoard , toFen , ChessBoard , Square (..) , BoardState (..) , getBoard ) where import Control.Monad.State (State, get, gets, put) import Data.List (find, sortBy) import System.Random (Random, RandomGen, StdGen, random, randomR) type Pos = (Char, In...
Convert the following code from C++ to Haskell, ensuring the logic remains intact.
#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; total *= ...
import Data.List (group, intercalate, transpose) import Data.List.Split (chunksOf) import Data.Numbers.Primes ( primeFactors ) import Text.Printf (printf) oeisA111398 :: [Integer] oeisA111398 = 1 : [n | n <- [1..], 8 == length (divisors n)] divisors :: Integer -> [Integer] divisors = foldr (flip ((<*>) . fm...
Transform the following C++ implementation into Haskell, maintaining the same output and logic.
#include <iomanip> #include <iostream> #include <boost/multiprecision/cpp_int.hpp> template <typename IntegerType> IntegerType arithmetic_derivative(IntegerType n) { bool negative = n < 0; if (negative) n = -n; if (n < 2) return 0; IntegerType sum = 0, count = 0, m = n; while ((m &...
import Control.Monad (forM_) import Data.List (intercalate) import Data.List.Split (chunksOf) import Math.NumberTheory.Primes (factorise, unPrime) import Text.Printf (printf) arithderiv_ :: Integer -> Integer arithderiv_ 0 = 0 arithderiv_ n = foldr step 0 $ factorise n where step (p, v) s = s + n `quot` unPrime p *...
Transform the following C++ implementation into Haskell, maintaining the same output and logic.
#include <iomanip> #include <iostream> #include <utility> auto min_max_prime_factors(unsigned int n) { unsigned int min_factor = 1; unsigned int max_factor = 1; if ((n & 1) == 0) { while ((n & 1) == 0) n >>= 1; min_factor = 2; max_factor = 2; } for (unsigned int ...
import Data.List (intercalate, transpose) import Data.List.Split (chunksOf) import Data.Numbers.Primes (primeFactors) import Text.Printf (printf) oeisA066048 :: [Integer] oeisA066048 = 1 : fmap f [2 ..] where f = ((*) . head <*> last) . primeFactors main :: IO () main = putStrLn $ table " " $ (chunksOf 1...
Write the same algorithm in Haskell as shown in this C++ implementation.
#include <iostream> #include <optional> using namespace std; class TropicalAlgebra { optional<double> m_value; public: friend std::ostream& operator<<(std::ostream&, const TropicalAlgebra&); friend TropicalAlgebra pow(const TropicalAlgebra& base, unsigned int exponent) noexcept; Tr...
import Prelude hiding ((^)) import Data.Monoid (Sum(Sum)) import Data.Number.CReal (CReal) import Data.Semiring (Semiring, (^), plus, times) import Data.Semiring.Tropical (Tropical(..), Extrema(Maxima)) newtype MaxPlus = MaxPlus (Tropical 'Maxima CReal) (βŠ•), (βŠ—) :: MaxPlus -> MaxPlus -> MaxPlus (βŠ•) = plus...
Convert this C++ snippet to Haskell and keep its semantics consistent.
#include <iomanip> #include <iostream> int prime_factor_sum(int n) { int sum = 0; for (; (n & 1) == 0; n >>= 1) sum += 2; for (int p = 3, sq = 9; sq <= n; p += 2) { for (; n % p == 0; n /= p) sum += p; sq += (p + 1) << 2; } if (n > 1) sum += n; return...
import qualified Data.Set as S import Data.List.Split ( chunksOf ) divisors :: Int -> [Int] divisors n = [d | d <- [2 .. n] , mod n d == 0] primeFactors :: Int -> [Int] primeFactors n = snd $ until ( (== 1) . fst ) step (n , [] ) where step :: (Int , [Int] ) -> (Int , [Int] ) step (n , li) = ( div n h , li ++ ...
Produce a language-to-language conversion: from C++ to Haskell, same semantics.
#include <algorithm> #include <iostream> int main() { std::string str("AABBBC"); int count = 0; do { std::cout << str << (++count % 10 == 0 ? '\n' : ' '); } while (std::next_permutation(str.begin(), str.end())); }
permutationsSomeIdentical :: [(a, Int)] -> [[a]] permutationsSomeIdentical [] = [[]] permutationsSomeIdentical xs = [ x : ys | (x, xs_) <- select xs, ys <- permutationsSomeIdentical xs_ ] where select [] = [] select ((x, n) : xs) = (x, xs_) : [ (y, (x, n) : cs) | (y, cs) ...
Port the provided C++ code into Haskell while preserving the original functionality.
#include <cctype> #include <cstdint> #include <iomanip> #include <iostream> #include <string> #include <vector> struct number_names { const char* cardinal; const char* ordinal; }; const number_names small[] = { { "zero", "zeroth" }, { "one", "first" }, { "two", "second" }, { "three", "third" }, { "fou...
import Data.Char sentence = start ++ foldMap add (zip [2..] $ tail $ words sentence) where start = "Four is the number of letters in the first word of this sentence, " add (i, w) = unwords [spellInteger (alphaLength w), "in the", spellOrdinal i ++ ", "] alphaLength w = fromIntegral $ length $ filter isAlpha...
Keep all operations the same but rewrite the snippet in Haskell.
class NG_8 : public matrixNG { private: int a12, a1, a2, a, b12, b1, b2, b, t; double ab, a1b1, a2b2, a12b12; const int chooseCFN(){return fabs(a1b1-ab) > fabs(a2b2-ab)? 0 : 1;} const bool needTerm() { if (b1==0 and b==0 and b2==0 and b12==0) return false; if (b==0){cfn = b2==0? 0:1; return tr...
data Term = InfiniteTerm | IntegerTerm Integer type ContinuedFraction = [Term] type NG8 = (Integer, Integer, Integer, Integer, Integer, Integer, Integer, Integer) cf2string (cf :: ContinuedFraction) = loop 0 "[" cf where loop i s lst = case lst of { (InfiniteTerm : _) -> s ...
Preserve the algorithm and functionality while converting the code from C++ to Haskell.
class NG_8 : public matrixNG { private: int a12, a1, a2, a, b12, b1, b2, b, t; double ab, a1b1, a2b2, a12b12; const int chooseCFN(){return fabs(a1b1-ab) > fabs(a2b2-ab)? 0 : 1;} const bool needTerm() { if (b1==0 and b==0 and b2==0 and b12==0) return false; if (b==0){cfn = b2==0? 0:1; return tr...
data Term = InfiniteTerm | IntegerTerm Integer type ContinuedFraction = [Term] type NG8 = (Integer, Integer, Integer, Integer, Integer, Integer, Integer, Integer) cf2string (cf :: ContinuedFraction) = loop 0 "[" cf where loop i s lst = case lst of { (InfiniteTerm : _) -> s ...
Preserve the algorithm and functionality while converting the code from C++ to Haskell.
#include <iomanip> #include <iostream> #include <boost/math/constants/constants.hpp> #include <boost/multiprecision/cpp_dec_float.hpp> using big_float = boost::multiprecision::cpp_dec_float_100; big_float f(unsigned int n) { big_float pi(boost::math::constants::pi<big_float>()); return exp(sqrt(big_float(n)) ...
import Control.Monad (forM_) import Data.Number.CReal (CReal, showCReal) import Text.Printf (printf) ramfun :: CReal -> CReal ramfun x = exp (pi * sqrt x) ramanujan :: CReal ramanujan = ramfun 163 heegners :: [Int] heegners = [19, 43, 67, 163] intDist :: CReal -> CReal intDist x = abs (x - fromIntegral (round x)...
Port the provided C++ code into Haskell while preserving the original functionality.
#include <iomanip> #include <iostream> #include <boost/math/constants/constants.hpp> #include <boost/multiprecision/cpp_dec_float.hpp> using big_float = boost::multiprecision::cpp_dec_float_100; big_float f(unsigned int n) { big_float pi(boost::math::constants::pi<big_float>()); return exp(sqrt(big_float(n)) ...
import Control.Monad (forM_) import Data.Number.CReal (CReal, showCReal) import Text.Printf (printf) ramfun :: CReal -> CReal ramfun x = exp (pi * sqrt x) ramanujan :: CReal ramanujan = ramfun 163 heegners :: [Int] heegners = [19, 43, 67, 163] intDist :: CReal -> CReal intDist x = abs (x - fromIntegral (round x)...
Convert the following code from C++ to Haskell, ensuring the logic remains intact.
#include <any> #include <iostream> #include <iterator> #include <vector> using namespace std; vector<any> MakeTree(input_iterator auto first, input_iterator auto last, int depth = 1) { vector<any> tree; while (first < last && depth <= *first) { if(*first == depth) { ...
import Data.Bifunctor (bimap) import Data.Tree (Forest, Tree (..), drawTree, foldTree) treeFromSparseLevels :: [Int] -> Tree (Maybe Int) treeFromSparseLevels = Node Nothing . forestFromNestLevels . rooted . normalised sparseLevelsFromTree :: Tree (Maybe Int) -> [Int] sparseLevelsFromTree = foldTree ...
Transform the following C++ implementation into Haskell, maintaining the same output and logic.
#include <any> #include <iostream> #include <iterator> #include <vector> using namespace std; vector<any> MakeTree(input_iterator auto first, input_iterator auto last, int depth = 1) { vector<any> tree; while (first < last && depth <= *first) { if(*first == depth) { ...
import Data.Bifunctor (bimap) import Data.Tree (Forest, Tree (..), drawTree, foldTree) treeFromSparseLevels :: [Int] -> Tree (Maybe Int) treeFromSparseLevels = Node Nothing . forestFromNestLevels . rooted . normalised sparseLevelsFromTree :: Tree (Maybe Int) -> [Int] sparseLevelsFromTree = foldTree ...
Write the same code in Haskell as shown below in C++.
#include <iomanip> #include <iostream> #include <list> #include <string> #include <vector> #include <utility> #include <vector> class nest_tree; bool operator==(const nest_tree&, const nest_tree&); class nest_tree { public: explicit nest_tree(const std::string& name) : name_(name) {} nest_tree& add_child(con...
import Data.List (span) data Nest a = Nest (Maybe a) [Nest a] deriving Eq instance Show a => Show (Nest a) where show (Nest (Just a) []) = show a show (Nest (Just a) s) = show a ++ show s show (Nest Nothing []) = "\"\"" show (Nest Nothing s) = "\"\"" ++ show s type Indent a = [(Int, a)] class Is...
Produce a language-to-language conversion: from C++ to Haskell, same semantics.
#include <string> #include <vector> #include <map> #include <iostream> #include <algorithm> #include <utility> #include <sstream> std::string mostFreqKHashing ( const std::string & input , int k ) { std::ostringstream oss ; std::map<char, int> frequencies ; for ( char c : input ) { frequencies[ c ] = st...
module MostFrequentK where import Data.List ( nub , sortBy ) import qualified Data.Set as S count :: Eq a => [a] -> a -> Int count [] x = 0 count ( x:xs ) k |x == k = 1 + count xs k |otherwise = count xs k orderedStatistics :: String -> [(Char , Int)] orderedStatistics s = sortBy myCriterion $ nub $ zip ...
Generate an equivalent Pascal version of this C code.
#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, next = 1; pr...
begin integer max, next, i; integer procedure countDivisors ( Integer value n ) ; begin integer count, i, i2; count := 0; i := 1; while begin i2 := i * i; i2 < n end do begin if n rem i = 0 then count := count + 2; i ...
Generate an equivalent Pascal version of this C code.
#include <stdlib.h> #include <string.h> #include <ctype.h> #include <stdio.h> #define TRUE 1 #define FALSE 0 #define max(a, b) ((a) > (b)Β ? (a)Β : (b)) #define min(a, b) ((a) < (b)Β ? (a)Β : (b)) double jaro(const char *str1, const char *str2) { int str1_len = strlen(str1); int str2_len = strlen(str2)...
program Jaro_distance; uses SysUtils, Math; function ssJaroWinkler(s1, s2: string): double; var l1, l2, match_distance, matches, i, k, trans: integer; bs1, bs2: array[1..255] of boolean; begin l1 := length(s1); l2 := length(s2); fillchar(bs1, sizeof(bs1), 0); fillchar(bs2, sizeof(bs2), 0); if l1 = 0 ...
Translate this program into Pascal but keep the logic exactly as in C.
struct RS232_data { unsigned carrier_detect : 1; unsigned received_data : 1; unsigned transmitted_data : 1; unsigned data_terminal_ready : 1; unsigned signal_ground : 1; unsigned data_set_ready : 1; unsigned request_to_send : 1; unsigned clear_to_send :...
program rs232(input, output, stdErr); type pin = (carrierDetect, receivedData, transmittedData, dataTerminalReady, signalGround, dataSetReady, requestToSend, clearToSend, ringIndicator); pins = set of pin; var signal: pins; signalMemoryStructure: word absolute signal; begin signal := []; include(s...
Translate the given C code snippet into Pascal without altering its behavior.
#include <stdio.h> unsigned int lpd(unsigned int n) { if (n<=1) return 1; int i; for (i=n-1; i>0; i--) if (n%i == 0) return i; } int main() { int i; for (i=1; i<=100; i++) { printf("%3d", lpd(i)); if (i % 10 == 0) printf("\n"); } return 0; }
program LarPropDiv; function LargestProperDivisor(n:NativeInt):NativeInt; var i,j: NativeInt; Begin i := 2; repeat If n Mod i = 0 then Begin LargestProperDivisor := n DIV i; EXIT; end; inc(i); until i*i > n; LargestProperDivisor := 1; end; var n : Uint32; begin for n := 1 to...
Keep all operations the same but rewrite the snippet in Pascal.
#include <stdio.h> inline int self_desc(unsigned long long xx) { register unsigned int d, x; unsigned char cnt[10] = {0}, dig[10] = {0}; for (d = 0; xx > ~0U; xx /= 10) cnt[ dig[d++] = xx % 10 ]++; for (x = xx; x; x /= 10) cnt[ dig[d++] = x % 10 ]++; while(d-- && dig[x++] == cnt[d]); return d == -1; ...
Program SelfDescribingNumber; uses SysUtils; function check(number: longint): boolean; var i, d: integer; a: string; count, w : array [0..9] of integer; begin a := intToStr(number); for i := 0 to 9 do begin count[i] := 0; w[i] := 0; end; for i := 1 to length(a) do ...
Port the provided C code into Pascal while preserving the original functionality.
#include <stdio.h> #define SIZE 256 int check(char *word) { int e = 0, ok = 1; for(; *word && ok; word++) { switch(*word) { case 'a': case 'i': case 'o': case 'u': ok = 0; break; case 'e': e++; } } return ok && e > 3; } ...
program EWords; var FileVar: Text; Line: string[255]; I: Integer; E: Integer; OK: Boolean; begin Assign(FileVar, 'unixdict.txt'); Reset(FileVar); while not Eof(FileVar) do begin ReadLn(FileVar, Line); E := 0; OK := True; for I := 1 to Length(Line) do begin ...
Generate an equivalent Pascal version of this C code.
#include <stdio.h> void mosaicMatrix(unsigned int n) { int i, j; for (i = 0; i < n; ++i) { for (j = 0; j < n; ++j) { if ((i + j) % 2 == 0) { printf("%s ", "1"); } else { printf("%s ", "0"); } } printf("\n"); } } in...
program mosaicMatrix(output); const filledCell = '1'; emptyCell = 'β‹…'; procedure printMosaicMatrix(dimension: integer); var line: integer; begin for line := 1 to dimension do begin for dimension := 1 to dimension do begin if odd(dimension + ord(odd(line))) then begin write(emptyCell) ...
Can you help me rewrite this code in Pascal instead of C, keeping it the same logically?
#include<stdlib.h> #include<stdio.h> #define LEN 100 int main() { char **list; int num, i; scanf("%d",&num); list = (char**)malloc(num*sizeof(char*)); for(i=0;i<num;i++) { list[i] = (char*)malloc(LEN*sizeof(char)); fflush(stdin); fgets(list[i],LEN,stdin); } printf("\n"); for(i=0;i<...
program head(input, output, stdErr); type obj = object public procedure method(const s: string); static; end; procedure obj.method(const s: string); begin writeLn(s); end; var numberOfLines: integer; line: string; begin readLn(numberOfLines); for numberOfLines := numberOfLines downto 1 do begin r...
Maintain the same structure and functionality when rewriting this code in Pascal.
#include <stdio.h> int divisible(int n) { int p = 1; int c, d; for (c=n; c; c /= 10) { d = c % 10; if (!d || n % d) return 0; p *= d; } return n % p; } int main() { int n, c=0; for (n=1; n<1000; n++) { if (divisible(n)) { printf("%...
program DivByDgtsNotByProdOfDgts; function ProdDigits(n:cardinal):cardinal; var p,q,r,dgt : cardinal; begin q := n; p := 1; repeat r := q DIV 10; dgt := q-10*r; if (dgt= 0)OR(n mod dgt <> 0) then EXIT(0); p := p*dgt; q := r; until q = 0; Exit(p) end; const LimitLow = 1; ...
Keep all operations the same but rewrite the snippet in Pascal.
#include <stdio.h> #include <stdlib.h> #include <stdint.h> #include <time.h> #define DIGITS 1000 #define NUMSIZE 5 uint8_t randomDigit() { uint8_t d; do {d = rand() & 0xF;} while (d >= 10); return d; } int numberAt(uint8_t *d, int size) { int acc = 0; while (size--) acc = 10*acc + *d++; retur...
var digits, s : AnsiString; i : LongInt; begin randomize; setlength(digits,1000); for i := 1 to 1000 do digits[i] := chr(random(10)+ord('0')); for i := 99999 downto 0 do begin str(i:5,s); if Pos(s,digits) > 0 then break; end; writeln(s, ' found as largest 5 digit number ') end.
Write the same code in Pascal as shown below in C.
#include <stdio.h> void lshift(int *l, size_t n) { int i, f; if (n < 2) return; f = l[0]; for (i = 0; i < n-1; ++i) l[i] = l[i+1]; l[n-1] = f; } int main() { int l[] = {1, 2, 3, 4, 5, 6, 7, 8, 9}; int i; size_t n = 9; printf("Original list Β : "); for (i = 0; i < n; ++i) pri...
begin % increments a and returns the new value % integer procedure inc ( integer value result a ) ; begin a := a + 1; a end; % shifts in place the elements of a left by n, a must have bounds lb::ub % procedure rotateLeft ( integer array a ( * ); integer value lb, ub, n ) ; if n < ( ub - lb ) a...
Keep all operations the same but rewrite the snippet in Pascal.
#include <stdio.h> #define LIMIT 100000 int digitset(int num, int base) { int set; for (set = 0; num; num /= base) set |= 1 << num % base; return set; } int main() { int i, c = 0; for (i = 0; i < LIMIT; i++) if (digitset(i,10) == digitset(i,16)) printf("%6d%c", i, ++c%1...
program Dec_Hex_same_UsedDigits; const UpperLimit = 100*1000; type tUsedDigits = array[0..15] of byte; var FormCnt: Int32; UsedDigits : tUsedDigits; procedure Out_(n,h:Uint32); Begin write(n:11,':',h:7); inc(FormCnt); If FormCnt >= 4 then Begin FormCnt := 0; writeln; end; end; ...
Translate this program into Pascal but keep the logic exactly as in C.
#include <stdio.h> void specialMatrix(unsigned int n) { int i, j; for (i = 0; i < n; ++i) { for (j = 0; j < n; ++j) { if (i == j || i + j == n - 1) { printf("%d ", 1); } else { printf("%d ", 0); } } printf("\n"); } ...
program diagonaldiagonal; const N = 7; type index = 1..N; var a : array[index, index] of real; i, j, j1, j2 : index; begin for i := 1 to N do begin for j := 1 to N do a[i, j] := 0.0; j1 := i; j2 := N - i + 1; a[i, j1] := 1.0; a[i, j2] := 1.0; ...
Convert this C snippet to Pascal and keep its semantics consistent.
#include <stdio.h> #include <string.h> int main() { char word[128]; FILE *f = fopen("unixdict.txt","r"); if (!f) { fprintf(stderr, "Cannot open unixdict.txt\n"); return -1; } while (!feof(f)) { fgets(word, sizeof(word), f); if (strlen(word) > 12 && ...
program wordsContainingTheSubstring(input, output); var word: string(22); begin while not EOF do begin readLn(word); if (length(word) > 11) and_then (index(word, 'the') > 0) then begin writeLn(word) end end end.
Generate a Pascal translation of this C snippet without changing its computational steps.
#include <locale.h> #include <stdio.h> int main() { unsigned long long int trillion = 1000000000000; setlocale(LC_NUMERIC,""); printf("LocaleΒ : %s, One TrillionΒ :Β %'llu\n", setlocale(LC_CTYPE,NULL),trillion); return 0; }
program test; begin WriteLn(%1001_1001); WriteLn(&121_102); WriteLn(-1_123_123); WriteLn($1_123_123); WriteLn(-1_123___123.000_000); WriteLn(1_123_123.000_000e1_2); end.
Produce a language-to-language conversion: from C to Pascal, same semantics.
#include <stdio.h> #include <string.h> char *uniques(char *str[], char *buf) { static unsigned counts[256]; unsigned i; char *s, *o = buf; memset(counts, 0, 256 * sizeof(unsigned)); for (; *str; str++) for (s = *str; *s; s++) counts[(unsigned) *s]++; for (i=0; i<25...
program uniqueCharacters(output); type integerNonNegative = 0..maxInt; integerPositive = 1..maxInt value 1; charFrequency = array[char] of integerNonNegative; line = string(80); lines(length: integerPositive) = array[1..length] of line; function createStatistics(protected sample: lines): charFrequen...
Change the following C code into Pascal without altering its purpose.
#include <stdio.h> #include <stdlib.h> #include <math.h> #include <string.h> typedef unsigned char u8t; typedef unsigned short u16t; enum { NR=4, NC=4, NCELLS = NR*NC }; enum { UP, DOWN, LEFT, RIGHT, NDIRS }; enum { OK = 1<<8, XX = 1<<9, FOUND = 1<<10, zz=0x80 }; enum { MAX_INT=0x7E, MAX_NODES=(16*65536)*90}; enum {...
unit FifteenSolverT; \\ Solve 15 Puzzle. Nigel Galloway; February 1st., 2019. interface type TN=record n:UInt64; i,g,e,l:shortint; end; type TG=record found:boolean; path:array[0..99] of TN; end; function solve15(const board : UInt64; const bPos:shortint; const d:shortint; const ng:shortint):TG; const endPos:UInt64=$12...
Maintain the same structure and functionality when rewriting this code in Pascal.
double multiply(double a, double b) { return a * b; }
function multiply(a, b: real): real; begin multiply := a * b end;