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 <iostream> #include <string> #include <windows.h> using namespace std; class bells { public: void start() { watch[0] = "Middle"; watch[1] = "Morning"; watch[2] = "Forenoon"; watch[3] = "Afternoon"; watch[4] = "Dog"; watch[5] = "First"; count[0] = "One"; count[1] = "Two"; count[2] = "Three"; cou...
import Control.Concurrent import Control.Monad import Data.Time import Text.Printf type Microsecond = Int type Scheduler = TimeOfDay -> Microsecond getTime :: TimeZone -> IO TimeOfDay getTime tz = do t <- getCurrentTime return $ localTimeOfDay $ utcToLocalTime tz t getGMTTime = getTime utc getLocalTime...
Change the programming language of this snippet from C++ to Haskell without modifying what it does.
#include <iostream> #include <string> #include <windows.h> using namespace std; class bells { public: void start() { watch[0] = "Middle"; watch[1] = "Morning"; watch[2] = "Forenoon"; watch[3] = "Afternoon"; watch[4] = "Dog"; watch[5] = "First"; count[0] = "One"; count[1] = "Two"; count[2] = "Three"; cou...
import Control.Concurrent import Control.Monad import Data.Time import Text.Printf type Microsecond = Int type Scheduler = TimeOfDay -> Microsecond getTime :: TimeZone -> IO TimeOfDay getTime tz = do t <- getCurrentTime return $ localTimeOfDay $ utcToLocalTime tz t getGMTTime = getTime utc getLocalTime...
Ensure the translated Haskell code behaves exactly like the original C++ snippet.
#include <windows.h> #include <sstream> #include <ctime> const float PI = 3.1415926536f, TWO_PI = 2.f * PI; class vector2 { public: vector2( float a = 0, float b = 0 ) { set( a, b ); } void set( float a, float b ) { x = a; y = b; } void rotate( float r ) { float _x = x, _y = y, s = s...
import Reflex import Reflex.Dom import Reflex.Dom.Time import Data.Text (Text, pack) import Data.Map (Map, fromList) import Data.Time.Clock (getCurrentTime) import Control.Monad.Trans (liftIO) type Point = (Float,Float) type Segment = (Point,Point) main = mainWidget $ do dTick <- tickLossy 0.05 =<< liftIO ge...
Write the same code in Haskell as shown below in C++.
#include <windows.h> #include <sstream> #include <ctime> const float PI = 3.1415926536f, TWO_PI = 2.f * PI; class vector2 { public: vector2( float a = 0, float b = 0 ) { set( a, b ); } void set( float a, float b ) { x = a; y = b; } void rotate( float r ) { float _x = x, _y = y, s = s...
import Reflex import Reflex.Dom import Reflex.Dom.Time import Data.Text (Text, pack) import Data.Map (Map, fromList) import Data.Time.Clock (getCurrentTime) import Control.Monad.Trans (liftIO) type Point = (Float,Float) type Segment = (Point,Point) main = mainWidget $ do dTick <- tickLossy 0.05 =<< liftIO ge...
Please provide an equivalent version of this C++ code in Haskell.
#include <iostream> #include <optional> #include <ranges> #include <string> #include <vector> using namespace std; struct Patient { string ID; string LastName; }; struct Visit { string PatientID; string Date; optional<float> Score; }; int main(void) { auto patients = vector<Patient> { ...
import Data.List import Data.Maybe import System.IO (readFile) import Text.Read (readMaybe) import Control.Applicative ((<|>)) newtype DB = DB { entries :: [Patient] } deriving Show instance Semigroup DB where DB a <> DB b = normalize $ a <> b instance Monoid DB where mempty = DB [] normalize :: [Patient] -...
Please provide an equivalent version of this C++ code in Haskell.
#include <windows.h> #include <vector> #include <string> using namespace std; struct Point { int x, y; }; class MyBitmap { public: MyBitmap() : pen_(nullptr) {} ~MyBitmap() { DeleteObject(pen_); DeleteDC(hdc_); DeleteObject(bmp_); } bool Create(int w, int h) { BITMAPINFO bi; ZeroMem...
module Main where import System.Random import Data.Word import Data.Array.Repa as Repa import Data.Array.Repa.IO.BMP sqDistance :: Word32 -> Word32 -> Word32 -> Word32 -> Word32 sqDistance !x1 !y1 !x2 !y2 = ((x1-x2)^2) + ((y1-y2)^2) centers :: Int -> Int -> Array U DIM2 Word32 centers nCenters nCells = f...
Port the provided C++ code into Haskell while preserving the original functionality.
#include <windows.h> #include <vector> #include <string> using namespace std; struct Point { int x, y; }; class MyBitmap { public: MyBitmap() : pen_(nullptr) {} ~MyBitmap() { DeleteObject(pen_); DeleteDC(hdc_); DeleteObject(bmp_); } bool Create(int w, int h) { BITMAPINFO bi; ZeroMem...
module Main where import System.Random import Data.Word import Data.Array.Repa as Repa import Data.Array.Repa.IO.BMP sqDistance :: Word32 -> Word32 -> Word32 -> Word32 -> Word32 sqDistance !x1 !y1 !x2 !y2 = ((x1-x2)^2) + ((y1-y2)^2) centers :: Int -> Int -> Array U DIM2 Word32 centers nCenters nCells = f...
Generate a Haskell translation of this C++ snippet without changing its computational steps.
#include <iostream> #include <vector> #include <algorithm> #include <stdexcept> #include <memory> #include <sys/time.h> using std::cout; using std::endl; class StopTimer { public: StopTimer(): begin_(getUsec()) {} unsigned long long getTime() const { return getUsec() - begin_; } private: static unsigned l...
inv = [("map",9,150,1), ("compass",13,35,1), ("water",153,200,2), ("sandwich",50,60,2), ("glucose",15,60,2), ("tin",68,45,3), ("banana",27,60,3), ("apple",39,40,3), ("cheese",23,30,1), ("beer",52,10,3), ("cream",11,70,1), ("camera",32,30,1), ("tshirt",24,15,2), ("trousers",48,10,2), ("umbrella",73,40,1), ("wtrous...
Can you help me rewrite this code in Haskell instead of C++, keeping it the same logically?
#include <iostream> #include <sstream> #include <iterator> #include <vector> using namespace std; struct node { int val; unsigned char neighbors; }; class hSolver { public: hSolver() { dx[0] = -1; dx[1] = 0; dx[2] = 1; dx[3] = -1; dx[4] = 1; dx[5] = -1; dx[6] = 0; dx[7] = 1; dy[0] = -1; dy[1] = -...
import qualified Data.IntMap as I import Data.IntMap (IntMap) import Data.List import Data.Maybe import Data.Time.Clock data BoardProblem = Board { cells :: IntMap (IntMap Int) , endVal :: Int , onePos :: (Int, Int) , givens :: [Int] } deriving (Show, Eq) tupIns x y v m = I.insert x (I.insert y v (I.find...
Write the same code in Haskell as shown below in C++.
#include <iostream> #include <sstream> #include <iterator> #include <vector> using namespace std; struct node { int val; unsigned char neighbors; }; class hSolver { public: hSolver() { dx[0] = -1; dx[1] = 0; dx[2] = 1; dx[3] = -1; dx[4] = 1; dx[5] = -1; dx[6] = 0; dx[7] = 1; dy[0] = -1; dy[1] = -...
import qualified Data.IntMap as I import Data.IntMap (IntMap) import Data.List import Data.Maybe import Data.Time.Clock data BoardProblem = Board { cells :: IntMap (IntMap Int) , endVal :: Int , onePos :: (Int, Int) , givens :: [Int] } deriving (Show, Eq) tupIns x y v m = I.insert x (I.insert y v (I.find...
Preserve the algorithm and functionality while converting the code from C++ to Haskell.
#include <list> template <typename T> std::list<T> strandSort(std::list<T> lst) { if (lst.size() <= 1) return lst; std::list<T> result; std::list<T> sorted; while (!lst.empty()) { sorted.push_back(lst.front()); lst.pop_front(); for (typename std::list<T>::iterator it = lst.begin(); it != lst.en...
merge :: (Ord a) => [a] -> [a] -> [a] merge [] ys = ys merge xs [] = xs merge (x : xs) (y : ys) | x <= y = x : merge xs (y : ys) | otherwise = y : merge (x : xs) ys strandSort :: (Ord a) => [a] -> [a] strandSort [] = [] strandSort (x : xs) = merge strand (strandSort rest) where (strand, rest) = extractStrand x xs ...
Please provide an equivalent version of this C++ code in Haskell.
#include <functional> #include <iostream> #include <iomanip> #include <math.h> #include <sstream> #include <vector> #include <boost/algorithm/string.hpp> template<typename T> T normalize(T a, double b) { return std::fmod(a, b); } inline double d2d(double a) { return normalize<double>(a, 360); } inline double g2g(doub...
import Text.Printf class (Num a, Fractional a, RealFrac a) => Angle a where fullTurn :: a mkAngle :: Double -> a value :: a -> Double fromTurn :: Double -> a toTurn :: a -> Double normalize :: a -> a fromTurn t = angle t * fullTurn toTurn a = value $ a / fullTurn normalize a = a `modu...
Preserve the algorithm and functionality while converting the code from C++ to Haskell.
#include <cassert> #include <cstdlib> #include <iostream> #include <stdexcept> #include <utility> #include <vector> #include <libxml/parser.h> #include <libxml/tree.h> #include <libxml/xmlerror.h> #include <libxml/xmlstring.h> #include <libxml/xmlversion.h> #include <libxml/xpath.h> #ifndef LIBXML_XPATH_ENABLED # e...
import Data.List import Control.Arrow import Control.Monad takeWhileIncl :: (a -> Bool) -> [a] -> [a] takeWhileIncl _ [] = [] takeWhileIncl p (x:xs) | p x = x : takeWhileIncl p xs | otherwise = [x] getmultiLineItem n = takeWhileIncl(not.isInfixOf ("</" ++ n)). dropWhil...
Produce a functionally identical Haskell code for the snippet given in C++.
#include <algorithm> #include <iomanip> #include <iostream> #include <map> #include <ostream> #include <set> #include <vector> template<typename T> std::ostream& print(std::ostream& os, const T& src) { auto it = src.cbegin(); auto end = src.cend(); os << "["; if (it != end) { os << *it; ...
import Data.List (groupBy, sortBy, intercalate) type Item = (Int, String) type ItemList = [Item] type ItemGroups = [ItemList] type RankItem a = (a, Int, String) type RankItemList a = [RankItem a] prepare :: ItemList -> ItemGroups prepare = groupBy gf . sortBy (flip compare) where gf (a, _) (b, _) = a == b ...
Write a version of this C++ function in Haskell with identical behavior.
#include <iostream> #include <string> #include <map> #include <algorithm> using namespace std; class StraddlingCheckerboard { map<char, string> table; char first[10], second[10], third[10]; int rowU, rowV; public: StraddlingCheckerboard(const string &alphabet, int u, int v) { rowU = min(u, v); rowV...
import Data.Char import Data.Map charToInt :: Char -> Int charToInt c = ord c - ord '0' decodeChar :: String -> (Char,String) decodeChar ('7':'9':r:rs) = (r,rs) decodeChar ('7':r:rs) = ("PQUVWXYZ. " !! charToInt r, rs) decodeChar ('3':r:rs) = ("ABCDFGIJKN" !! charToInt r, rs) decodeChar (r:rs) = ("H...
Preserve the algorithm and functionality while converting the code from C++ to Haskell.
#include <iostream> #include <fstream> #include <string> #include <tuple> #include <vector> #include <stdexcept> #include <boost/regex.hpp> struct Claim { Claim(const std::string& name) : name_(name), pro_(0), against_(0), propats_(), againstpats_() { } void add_pro(const std::string...
import Network.HTTP import Text.Regex.TDFA import Text.Printf getWordList :: IO String getWordList = do response <- simpleHTTP.getRequest$ url getResponseBody response where url = "http://wiki.puzzlers.org/pub/wordlists/unixdict.txt" main = do words <- getWordList putStrLn "Checking Rule 1...
Generate an equivalent Haskell version of this C++ code.
#include <iostream> #include "xtensor/xarray.hpp" #include "xtensor/xio.hpp" #include "xtensor-io/ximage.hpp" xt::xarray<int> init_grid (unsigned long x_dim, unsigned long y_dim) { xt::xarray<int>::shape_type shape = { x_dim, y_dim }; xt::xarray<int> grid(shape); grid(x_dim/2, y_dim/2) = 64000; r...
module Rosetta.AbelianSandpileModel.ST ( simulate , test , toPGM ) where import Control.Monad.Reader (asks, MonadReader (..), ReaderT, runReaderT) import Control.Monad.ST (runST, ST) import Control.Monad.State (evalStateT, forM_, lift, MonadState (..), StateT, modify, when) import Data.Array.ST (f...
Write the same algorithm in Haskell as shown in this C++ implementation.
#include <iostream> #include "xtensor/xarray.hpp" #include "xtensor/xio.hpp" #include "xtensor-io/ximage.hpp" xt::xarray<int> init_grid (unsigned long x_dim, unsigned long y_dim) { xt::xarray<int>::shape_type shape = { x_dim, y_dim }; xt::xarray<int> grid(shape); grid(x_dim/2, y_dim/2) = 64000; r...
module Rosetta.AbelianSandpileModel.ST ( simulate , test , toPGM ) where import Control.Monad.Reader (asks, MonadReader (..), ReaderT, runReaderT) import Control.Monad.ST (runST, ST) import Control.Monad.State (evalStateT, forM_, lift, MonadState (..), StateT, modify, when) import Data.Array.ST (f...
Write the same code in Haskell as shown below in C++.
#include <algorithm> #include <iostream> #include <sstream> #include <gmpxx.h> using integer = mpz_class; std::string to_string(const integer& n) { std::ostringstream out; out << n; return out.str(); } integer next_highest(const integer& n) { std::string str(to_string(n)); if (!std::next_permuta...
import Data.List (nub, permutations, sort) digitShuffleSuccessors :: Integer -> [Integer] digitShuffleSuccessors n = (fmap . (+) <*> (nub . sort . concatMap go . permutations . show)) n where go ds | 0 >= delta = [] | otherwise = [delta] where delta = (read ds :: Integer) - n main :...
Change the programming language of this snippet from C++ to Haskell without modifying what it does.
#include <algorithm> #include <iostream> #include <sstream> #include <gmpxx.h> using integer = mpz_class; std::string to_string(const integer& n) { std::ostringstream out; out << n; return out.str(); } integer next_highest(const integer& n) { std::string str(to_string(n)); if (!std::next_permuta...
import Data.List (nub, permutations, sort) digitShuffleSuccessors :: Integer -> [Integer] digitShuffleSuccessors n = (fmap . (+) <*> (nub . sort . concatMap go . permutations . show)) n where go ds | 0 >= delta = [] | otherwise = [delta] where delta = (read ds :: Integer) - n main :...
Rewrite the snippet below in Haskell so it works the same as the original C++ code.
#include <iostream> #include <string> #include <cctype> #include <cstdint> typedef std::uint64_t integer; const char* small[] = { "zero", "one", "two", "three", "four", "five", "six", "seven", "eight", "nine", "ten", "eleven", "twelve", "thirteen", "fourteen", "fifteen", "sixteen", "seventeen", "eighteen"...
module Main where import Data.List (find) import Data.Char (toUpper) firstNums :: [String] firstNums = [ "zero", "one", "two", "three", "four", "five", "six", "seven", "eight", "nine", "ten", "eleven", "twelve", "thirteen", "fourteen", "fifteen", "sixteen", "seventeen", "eighteen", "nineteen" ] tens :: [Stri...
Convert the following code from C++ to Haskell, ensuring the logic remains intact.
#include <iomanip> #include <iostream> #define _USE_MATH_DEFINES #include <math.h> constexpr double degrees(double deg) { const double tau = 2.0 * M_PI; return deg * tau / 360.0; } const double part_ratio = 2.0 * cos(degrees(72)); const double side_ratio = 1.0 / (part_ratio + 2.0); struct Point { doubl...
import Graphics.Gloss pentaflake :: Int -> Picture pentaflake order = iterate transformation pentagon !! order where transformation = Scale s s . foldMap copy [0,72..288] copy a = Rotate a . Translate 0 x pentagon = Polygon [ (sin a, cos a) | a <- [0,2*pi/5..2*pi] ] x = 2*cos(pi/5) s = 1/(1+x) ...
Ensure the translated Haskell code behaves exactly like the original C++ snippet.
#include <iostream> #include <string> #include <time.h> using namespace std; namespace { void placeRandomly(char* p, char c) { int loc = rand() % 8; if (!p[loc]) p[loc] = c; else placeRandomly(p, c); } int placeFirst(char* p, char c, int loc = 0) { while (p[loc]) ++loc; p[loc] = ...
import Data.List import qualified Data.Set as Set data Piece = K | Q | R | B | N deriving (Eq, Ord, Show) isChess960 :: [Piece] -> Bool isChess960 rank = (odd . sum $ findIndices (== B) rank) && king > rookA && king < rookB where Just king = findIndex (== K) rank [rookA, rookB] = findIndices (== R) r...
Change the programming language of this snippet from C++ to Haskell without modifying what it does.
#include <iostream> #include <string> #include <cstdint> typedef std::uint64_t integer; struct number_names { const char* cardinal; const char* ordinal; }; const number_names small[] = { { "zero", "zeroth" }, { "one", "first" }, { "two", "second" }, { "three", "third" }, { "four", "fourth" }, { "five...
spellOrdinal :: Integer -> String spellOrdinal n | n <= 0 = "not ordinal" | n < 20 = small n | n < 100 = case divMod n 10 of (k, 0) -> spellInteger (10*k) ++ "th" (k, m) -> spellInteger (10*k) ++ "-" ++ spellOrdinal m | n < 1000 = case divMod n 100 of (k, 0) -> spellInteger (100*k) ++ "th" ...
Generate an equivalent Haskell version of this C++ code.
#include <boost/asio/ip/address.hpp> #include <cstdint> #include <iostream> #include <iomanip> #include <limits> #include <string> using boost::asio::ip::address; using boost::asio::ip::address_v4; using boost::asio::ip::address_v6; using boost::asio::ip::make_address; using boost::asio::ip::make_address_v4; using boo...
import Data.List (isInfixOf) import Numeric (showHex) import Data.Char (isDigit) data IPChunk = IPv6Chunk String | IPv4Chunk (String, String) | IPv6WithPort [IPChunk] String | IPv6NoPort [IPChunk] | IPv4WithPort IPChunk String | IPv4NoPort IPChunk | IPInvalid | IPZeroSection | IPUndefinedWithPort String | ...
Produce a language-to-language conversion: from C++ to Haskell, same semantics.
#include <iostream> #include <utility> #include <vector> using Point = std::pair<double, double>; constexpr auto eps = 1e-14; std::ostream &operator<<(std::ostream &os, const Point &p) { auto x = p.first; if (x == 0.0) { x = 0.0; } auto y = p.second; if (y == 0.0) { y = 0.0; } ...
import Data.Tuple.Curry main :: IO () main = mapM_ putStrLn $ concatMap (("" :) . uncurryN task) [ ((-10, 11), (10, -9), ((3, -5), 3)) , ((-10, 11), (-11, 12), ((3, -5), 3)) , ((3, -2), (7, -2), ((3, -5), 3)) , ((3, -2), (7, -2), ((0, 0), 4)) , ((0, -3), (0, 6), ((0, 0), 4)) , ((6, 3), ...
Can you help me rewrite this code in Haskell instead of C++, keeping it the same logically?
#include <iostream> #include <cstring> int findNumOfDec(const char *s) { int pos = 0; while (s[pos] && s[pos++] != '.') {} return strlen(s + pos); } void test(const char *s) { int num = findNumOfDec(s); const char *p = num != 1 ? "s" : ""; std::cout << s << " has " << num << " decimal" << p <...
decimal :: String -> Int decimal [] = 0 decimal ('.':xs) = length xs decimal (_:xs) = decimal xs numDecimal :: Double -> Int numDecimal = decimal . show main = print . map numDecimal $ [12.0, 12.345, 12.3450, 12.345555555555, 12.34555555555555555555, 1.2345e+54]
Change the following C++ code into Haskell without altering its purpose.
#include <boost/spirit.hpp> #include <boost/spirit/tree/ast.hpp> #include <string> #include <cassert> #include <iostream> #include <istream> #include <ostream> using boost::spirit::rule; using boost::spirit::parser_tag; using boost::spirit::ch_p; using boost::spirit::real_p; using boost::spirit::tree_no...
import Text.Parsec import Text.Parsec.Expr import Text.Parsec.Combinator import Data.Functor import Data.Function (on) data Exp = Num Int | Add Exp Exp | Sub Exp Exp | Mul Exp Exp | Div Exp Exp expr :: Stream s m Char => ParsecT s u m Exp expr = buildExpressionParser ta...
Rewrite the snippet below in Haskell so it works the same as the original C++ code.
#include <boost/spirit.hpp> #include <boost/spirit/tree/ast.hpp> #include <string> #include <cassert> #include <iostream> #include <istream> #include <ostream> using boost::spirit::rule; using boost::spirit::parser_tag; using boost::spirit::ch_p; using boost::spirit::real_p; using boost::spirit::tree_no...
import Text.Parsec import Text.Parsec.Expr import Text.Parsec.Combinator import Data.Functor import Data.Function (on) data Exp = Num Int | Add Exp Exp | Sub Exp Exp | Mul Exp Exp | Div Exp Exp expr :: Stream s m Char => ParsecT s u m Exp expr = buildExpressionParser ta...
Keep all operations the same but rewrite the snippet in Haskell.
#include <map> #include <iostream> #include <string> int main() { std::map<char, std::string> rep = {{'a', "DCaBA"}, {'b', "E"}, {'r', "Fr"}}; std::string magic = "abracadabra"; for(auto it = magic.begin(); it != magic.end(); ++it) { if(auto f = rep.find(*it); f != rep.end() && !f->second...
import Data.List (mapAccumL) import qualified Data.Map.Strict as M import Data.Maybe (fromMaybe) nthCharsReplaced :: M.Map Char [Maybe Char] -> String -> String nthCharsReplaced ruleMap = snd . mapAccumL go ruleMap where go a c = case M.lookup c a of Nothing -> (a, c) Just [] -> (a, c) ...
Ensure the translated Haskell code behaves exactly like the original C++ snippet.
#include <map> #include <iostream> #include <string> int main() { std::map<char, std::string> rep = {{'a', "DCaBA"}, {'b', "E"}, {'r', "Fr"}}; std::string magic = "abracadabra"; for(auto it = magic.begin(); it != magic.end(); ++it) { if(auto f = rep.find(*it); f != rep.end() && !f->second...
import Data.List (mapAccumL) import qualified Data.Map.Strict as M import Data.Maybe (fromMaybe) nthCharsReplaced :: M.Map Char [Maybe Char] -> String -> String nthCharsReplaced ruleMap = snd . mapAccumL go ruleMap where go a c = case M.lookup c a of Nothing -> (a, c) Just [] -> (a, c) ...
Change the programming language of this snippet from C++ to Haskell without modifying what it does.
#include <stdio.h> #include <stdlib.h> void clear() { for(int n = 0;n < 10; n++) { printf("\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\r\n\r\n\r\n"); } } #define UP "00^00\r\n00|00\r\n00000\r\n" #define DOWN "00000\r\n00|00\r\n00v00\r\n" #define LEFT "00000\r\n<--00\r\n00000\r\n" #define RIGHT "00000\r\n00-->\r\n00000\r\...
import qualified Graphics.UI.GLFW as GLFW import Graphics.Win32.Key import Control.Monad.RWS.Strict (liftIO) main = do liftIO $ do _ <- GLFW.init GLFW.pollEvents (jxrot, jyrot) <- liftIO $ getJoystickDirections GLFW.Joystick'1 putStrLn $ (show jxrot) ++ " " ++ (show jyrot)...
Change the following C++ code into Haskell without altering its purpose.
#include <iostream> #include <set> #include <tuple> #include <vector> using namespace std; template<typename P> void PrintPayloads(const P &payloads, int index, bool isLast) { if(index < 0 || index >= (int)size(payloads)) cout << "null"; else cout << "'" << payloads[index] << "'"; if (!isLast) co...
data Template a = Val a | List [Template a] deriving ( Show , Functor , Foldable , Traversable )
Change the programming language of this snippet from C++ to Haskell without modifying what it does.
#include <iostream> struct fraction { fraction(int n, int d) : numerator(n), denominator(d) {} int numerator; int denominator; }; std::ostream& operator<<(std::ostream& out, const fraction& f) { out << f.numerator << '/' << f.denominator; return out; } class farey_sequence { public: explicit ...
import Data.List (unfoldr, mapAccumR) import Data.Ratio ((%), denominator, numerator) import Text.Printf (PrintfArg, printf) farey :: Integer -> [Rational] farey n = 0 : unfoldr step (0, 1, 1, n) where step (a, b, c, d) | c > n = Nothing | otherwise = let k = (n + b) `quot` d in Just...
Maintain the same structure and functionality when rewriting this code in Haskell.
#include <iostream> struct fraction { fraction(int n, int d) : numerator(n), denominator(d) {} int numerator; int denominator; }; std::ostream& operator<<(std::ostream& out, const fraction& f) { out << f.numerator << '/' << f.denominator; return out; } class farey_sequence { public: explicit ...
import Data.List (unfoldr, mapAccumR) import Data.Ratio ((%), denominator, numerator) import Text.Printf (PrintfArg, printf) farey :: Integer -> [Rational] farey n = 0 : unfoldr step (0, 1, 1, n) where step (a, b, c, d) | c > n = Nothing | otherwise = let k = (n + b) `quot` d in Just...
Produce a functionally identical Haskell code for the snippet given in C++.
#include <cstdint> #include <iostream> #include <string> using integer = uint64_t; integer divisor_sum(integer n) { integer total = 1, power = 2; for (; n % 2 == 0; power *= 2, n /= 2) total += power; for (integer p = 3; p * p <= n; p += 2) { integer sum = 1; for (power ...
divisors :: (Integral a) => a -> [a] divisors n = filter ((0 ==) . (n `mod`)) [1 .. (n `div` 2)] data Class = Terminating | Perfect | Amicable | Sociable | Aspiring | Cyclic | Nonterminating deriving (Show) aliquot :: (Integral a) => a -> [a] aliquot 0 = [0] aliquot n = n : (aliquot $ sum $ divisors n...
Convert this C++ snippet to Haskell and keep its semantics consistent.
#include <cstdint> #include <iostream> #include <string> using integer = uint64_t; integer divisor_sum(integer n) { integer total = 1, power = 2; for (; n % 2 == 0; power *= 2, n /= 2) total += power; for (integer p = 3; p * p <= n; p += 2) { integer sum = 1; for (power ...
divisors :: (Integral a) => a -> [a] divisors n = filter ((0 ==) . (n `mod`)) [1 .. (n `div` 2)] data Class = Terminating | Perfect | Amicable | Sociable | Aspiring | Cyclic | Nonterminating deriving (Show) aliquot :: (Integral a) => a -> [a] aliquot 0 = [0] aliquot n = n : (aliquot $ sum $ divisors n...
Preserve the algorithm and functionality while converting the code from C++ to Haskell.
#include <iomanip> #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; ...
import Data.List.Split ( chunksOf ) import Data.List ( (!!) ) isPrime :: Int -> Bool isPrime n |n == 2 = True |n == 1 = False |otherwise = null $ filter (\i -> mod n i == 0 ) [2 .. root] where root :: Int root = floor $ sqrt $ fromIntegral n isMagnanimous :: Int -> Bool isMagnanimous n = a...
Generate a Haskell translation of this C++ snippet without changing its computational steps.
#include <iostream> bool isPrime(uint64_t n) { if (n < 2) return false; if (n % 2 == 0) return n == 2; if (n % 3 == 0) return n == 3; uint64_t test = 5; while (test * test < n) { if (n % test == 0) return false; test += 2; if (n % test == 0) return false; test += 4;...
import Data.Numbers.Primes (primes) import Text.Printf (printf) lucasLehmer :: Int -> Bool lucasLehmer p = iterate f 4 !! p-2 == 0 where f b = (b^2 - 2) `mod` m m = 2^p - 1 main = mapM_ (printf "M %d\n") $ take 20 mersenne where mersenne = filter lucasLehmer primes
Ensure the translated Haskell code behaves exactly like the original C++ snippet.
#include <iostream> bool isPrime(uint64_t n) { if (n < 2) return false; if (n % 2 == 0) return n == 2; if (n % 3 == 0) return n == 3; uint64_t test = 5; while (test * test < n) { if (n % test == 0) return false; test += 2; if (n % test == 0) return false; test += 4;...
import Data.Numbers.Primes (primes) import Text.Printf (printf) lucasLehmer :: Int -> Bool lucasLehmer p = iterate f 4 !! p-2 == 0 where f b = (b^2 - 2) `mod` m m = 2^p - 1 main = mapM_ (printf "M %d\n") $ take 20 mersenne where mersenne = filter lucasLehmer primes
Write the same code in Haskell as shown below in C++.
#include <array> #include <iostream> #include <vector> #include <boost/circular_buffer.hpp> #include "prime_sieve.hpp" int main() { using std::cout; using std::vector; using boost::circular_buffer; using group_buffer = circular_buffer<vector<int>>; const int max = 1000035; const int max_group_...
import Text.Printf (printf) import Data.Numbers.Primes (isPrime, primes) type Pair = (Int, Int) type Triplet = (Int, Int, Int) type Quad = (Int, Int, Int, Int) type Quin = (Int, Int, Int, Int, Int) type Result = ([Pair], [Triplet], [Quad], [Quin], [Int]) groups :: Int -> Result -> Result groups n r@(p, t, q,...
Write the same code in Haskell as shown below in C++.
#include <algorithm> #include <iomanip> #include <iostream> #include <map> #include <sstream> #include <vector> template <typename T> size_t indexOf(const std::vector<T> &v, const T &k) { auto it = std::find(v.cbegin(), v.cend(), k); if (it != v.cend()) { return it - v.cbegin(); } return -1; }...
import Data.List (groupBy, sortOn, tails, transpose) import Data.Function (on) taxis :: Int -> [[(Int, ((Int, Int), (Int, Int)))]] taxis nCubes = filter ((> 1) . length) $ groupBy (on (==) fst) $ sortOn fst [ (fst x + fst y, (x, y)) | (x:t) <- tails $ ((^ 3) >>= (,)) <$> [1 .. nCubes] , y <- t ] ...
Generate a Haskell translation of this C++ snippet without changing its computational steps.
#include <algorithm> #include <iostream> #include <iterator> #include <locale> #include <vector> #include "prime_sieve.hpp" const int limit1 = 1000000; const int limit2 = 10000000; class prime_info { public: explicit prime_info(int max) : max_print(max) {} void add_prime(int prime); void print(std::ostrea...
import Text.Printf (printf) import Data.Numbers.Primes (primes) xPrimes :: (Real a, Fractional b) => (b -> b -> Bool) -> [a] -> [a] xPrimes op ps@(p1:p2:p3:xs) | realToFrac p2 `op` (realToFrac (p1 + p3) / 2) = p2 : xPrimes op (tail ps) | otherwise = xPrimes op (tail ps) main :: IO () main = do printf "First 36...
Convert this C++ snippet to Haskell and keep its semantics consistent.
#include <vector> #include <string> #include <algorithm> #include <iostream> #include <sstream> using namespace std; #if 1 typedef unsigned long usingle; typedef unsigned long long udouble; const int word_len = 32; #else typedef unsigned short usingle; typedef unsigned long udouble; const int word_len = 16; #endif ...
leftFact :: [Integer] leftFact = scanl (+) 0 fact fact :: [Integer] fact = scanl (*) 1 [1 ..] main :: IO () main = mapM_ putStrLn [ "0 ~ 10:" , show $ (leftFact !!) <$> [0 .. 10] , "" , "20 ~ 110 by tens:" , unlines $ show . (leftFact !!) <$> [20,30 .. 110] , "" , "length of 1,000 ~ ...
Produce a functionally identical Haskell code for the snippet given in C++.
#include <vector> #include <string> #include <algorithm> #include <iostream> #include <sstream> using namespace std; #if 1 typedef unsigned long usingle; typedef unsigned long long udouble; const int word_len = 32; #else typedef unsigned short usingle; typedef unsigned long udouble; const int word_len = 16; #endif ...
leftFact :: [Integer] leftFact = scanl (+) 0 fact fact :: [Integer] fact = scanl (*) 1 [1 ..] main :: IO () main = mapM_ putStrLn [ "0 ~ 10:" , show $ (leftFact !!) <$> [0 .. 10] , "" , "20 ~ 110 by tens:" , unlines $ show . (leftFact !!) <$> [20,30 .. 110] , "" , "length of 1,000 ~ ...
Convert this C++ block to Haskell, preserving its control flow and logic.
#include <cstdint> #include <iomanip> #include <iostream> 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) return false; p += ...
import Control.Monad.Memo (Memo, memo, startEvalMemo) import Math.NumberTheory.Primes.Testing (isPrime) import System.Environment (getArgs) import Text.Printf (printf) type I = Integer motzkin :: I -> Memo I I I motzkin 0 = return 1 motzkin 1 = return 1 motzkin n = do m1 <- memo motzkin (n-1) m2 <- memo motzkin...
Ensure the translated Haskell code behaves exactly like the original C++ snippet.
#include <iostream> #include <vector> const std::vector<bool> p{ false, false, true, true, false, true, false, true, false, false, false, true, false, true, false, false, false, true, false }; bool isStrange(long n) { if (n < 10) { return false; } for (; n >= 10; n /= 10) { ...
import Data.List (intercalate) import Data.List.Split (chunksOf) isStrangePlus :: Int -> Bool isStrangePlus n = all (\(a, b) -> (a + b) `elem` [2, 3, 5, 7, 11, 13, 17]) $ (zip <*> tail) (digits n) digits :: Int -> [Int] digits = fmap (read . return) . show main = let xs = filter isStrangePlus [100 .....
Preserve the algorithm and functionality while converting the code from C++ to Haskell.
#include <iostream> #include <vector> const std::vector<bool> p{ false, false, true, true, false, true, false, true, false, false, false, true, false, true, false, false, false, true, false }; bool isStrange(long n) { if (n < 10) { return false; } for (; n >= 10; n /= 10) { ...
import Data.List (intercalate) import Data.List.Split (chunksOf) isStrangePlus :: Int -> Bool isStrangePlus n = all (\(a, b) -> (a + b) `elem` [2, 3, 5, 7, 11, 13, 17]) $ (zip <*> tail) (digits n) digits :: Int -> [Int] digits = fmap (read . return) . show main = let xs = filter isStrangePlus [100 .....
Please provide an equivalent version of this C++ code in Haskell.
#include <iostream> #include <cstdint> using integer = uint32_t; integer next_prime_digit_number(integer n) { if (n == 0) return 2; switch (n % 10) { case 2: return n + 1; case 3: case 5: return n + 2; default: return 2 + next_prime_digit_number(n/10) * 10; ...
import Control.Monad (guard) import Math.NumberTheory.Primes.Testing (isPrime) import Data.List.Split (chunksOf) import Data.List (intercalate) import Text.Printf (printf) smarandache :: [Integer] smarandache = [2,3,5,7] <> s [2,3,5,7] >>= \x -> guard (isPrime x) >> [x] where s xs = r <> s r where r = xs >>= \x -> [...
Keep all operations the same but rewrite the snippet in Haskell.
#include <iostream> #include <sstream> #include <iomanip> using namespace std; class magicSqr { public: magicSqr( int d ) { while( d % 4 > 0 ) { d++; } sz = d; sqr = new int[sz * sz]; fillSqr(); } ~magicSqr() { delete [] sqr; } void display() const { cout << "D...
import Data.List (transpose, unfoldr, intercalate) import Data.List.Split (chunksOf) import Data.Bool (bool) import Control.Monad (forM_) magicSquare :: Int -> [[Int]] magicSquare n | rem n 4 > 0 = [] | otherwise = chunksOf n $ zipWith (flip (bool =<< (-) limit)) series [1 .. sqr] where sqr = n * n l...
Write a version of this C++ function in Haskell with identical behavior.
#include <cstdint> #include <iostream> #include <string> using integer = uint64_t; bool square_free(integer n) { if (n % 4 == 0) return false; for (integer p = 3; p * p <= n; p += 2) { integer count = 0; for (; n % p == 0; n /= p) { if (++count > 1) return f...
import Data.List.Split (chunksOf) import Math.NumberTheory.Primes (factorise) import Text.Printf (printf) isSquareFree :: Integer -> Bool isSquareFree = all ((== 1) . snd) . factorise squareFrees :: Integer -> Integer -> [Integer] squareFrees lo hi = filter isSquareFree [lo..hi] counts :: (Ord a, Num b) => [a] ...
Can you help me rewrite this code in Haskell instead of C++, keeping it the same logically?
#include <array> #include <iomanip> #include <iostream> const int MC = 103 * 1000 * 10000 + 11 * 9 + 1; std::array<bool, MC + 1> SV; void sieve() { std::array<int, 10000> dS; for (int a = 9, i = 9999; a >= 0; a--) { for (int b = 9; b >= 0; b--) { for (int c = 9, s = a + b; c >= 0; c--) { ...
import Control.Monad (forM_) import Text.Printf selfs :: [Integer] selfs = sieve (sumFs [0..]) [0..] where sumFs = zipWith (+) [ a+b+c+d+e+f+g+h+i+j | a <- [0..9] , b <- [0..9] , c <- [0..9] , d <- [0..9] , e <- [0..9] , f <- [0..9] ...
Ensure the translated Haskell code behaves exactly like the original C++ snippet.
#include <cstdint> #include <iomanip> #include <iostream> uint64_t digit_sum(uint64_t n, uint64_t sum) { ++sum; while (n > 0 && n % 10 == 0) { sum -= 9; n /= 10; } return sum; } inline bool divisible(uint64_t n, uint64_t d) { if ((d & 1) == 0 && (n & 1) == 1) return false...
import Control.Monad (guard) import Text.Printf (printf) import Data.List (intercalate, unfoldr) import Data.List.Split (chunksOf) import Data.Tuple (swap) nivens :: [Int] nivens = [1..] >>= \n -> guard (n `rem` digitSum n == 0) >> [n] where digitSum = sum . unfoldr (\x -> guard (x > 0) >> pure (swap $ x `quotRem`...
Rewrite the snippet below in Haskell so it works the same as the original C++ code.
#include <iostream> #include <iomanip> using namespace std; class ormConverter { public: ormConverter() : AR( 0.7112f ), CE( 0.01f ), DI( 0.0254f ), FU( 0.3048f ), KI( 1000.0f ), LI( 0.00254f ), ME( 1.0f ), MI( 7467.6f ), PI( 0.1778f ), SA( 2.1336f ), TO( 0.000254f ), VE( 0.04445f ), VR( 1066.8f ) {} ...
module Main where import Text.Printf (printf) import System.Environment (getArgs, getProgName) tochka = ("tochka" , 0.000254) liniya = ("liniya" , 0.00254) centimeter = ("centimeter", 0.01) diuym = ("diuym" , 0.0254) vershok = ("vershok" , 0.04445) piad = ("piad" , 0.1778) fut ...
Generate an equivalent Haskell version of this C++ code.
#include <iomanip> #include <iostream> int digit_sum(int n) { int sum = 0; for (; n > 0; n /= 10) sum += n % 10; return sum; } int main() { for (int n = 1; n <= 70; ++n) { for (int m = 1;; ++m) { if (digit_sum(m * n) == n) { std::cout << std::setw(8) << m <<...
import Data.Bifunctor (first) import Data.List (elemIndex, intercalate, transpose) import Data.List.Split (chunksOf) import Data.Maybe (fromJust) import Text.Printf (printf) a131382 :: [Int] a131382 = fromJust . (elemIndex <*> productDigitSums) <$> [1 ..] productDigitSums :: Int -> [Int] productDigitSums n = ...
Generate a Haskell translation of this C++ snippet without changing its computational steps.
#include <iostream> #include <vector> constexpr int N = 2200; constexpr int N2 = 2 * N * N; int main() { using namespace std; vector<bool> found(N + 1); vector<bool> aabb(N2 + 1); int s = 3; for (int a = 1; a < N; ++a) { int aa = a * a; for (int b = 1; b < N; ++b) { ...
powersOfTwo :: [Int] powersOfTwo = iterate (2 *) 1 unrepresentable :: [Int] unrepresentable = merge powersOfTwo ((5 *) <$> powersOfTwo) merge :: [Int] -> [Int] -> [Int] merge xxs@(x:xs) yys@(y:ys) | x < y = x : merge xs yys | otherwise = y : merge xxs ys main :: IO () main = do putStrLn "The values of d <= 220...
Translate the given C++ code snippet into Haskell without altering its behavior.
#include <algorithm> #include <iostream> #include <map> #include <vector> std::ostream &operator<<(std::ostream &os, std::vector<std::pair<int, int>> &v) { for (auto &p : v) { auto sum = p.first + p.second; auto prod = p.first * p.second; os << '[' << p.first << ", " << p.second << "] S=" <...
import Data.List (intersect) s1, s2, s3, s4 :: [(Int, Int)] s1 = [(x, y) | x <- [1 .. 100], y <- [1 .. 100], 1 < x && x < y && x + y < 100] add, mul :: (Int, Int) -> Int add (x, y) = x + y mul (x, y) = x * y sumEq, mulEq :: (Int, Int) -> [(Int, Int)] sumEq p = filter (\q -> add q == add p) s1 mulEq p = filter (\q ->...
Please provide an equivalent version of this C++ code in Haskell.
#include <complex> #include <math.h> #include <iostream> template<class Type> struct Precision { public: static Type GetEps() { return eps; } static void SetEps(Type e) { eps = e; } private: static Type eps; }; template<class Type> Type Precision<Type>::eps = static_cast<Type>(1E-7); template<class DigT...
import Data.Decimal import Data.Ratio import Data.Complex
Transform the following C++ implementation into Haskell, maintaining the same output and logic.
#include <fstream> #include <iostream> #include <numeric> #include <unistd.h> #include <vector> std::vector<size_t> get_cpu_times() { std::ifstream proc_stat("/proc/stat"); proc_stat.ignore(5, ' '); std::vector<size_t> times; for (size_t time; proc_stat >> time; times.push_back(time)); return time...
import Data.List ( (!!) ) splitString :: Char -> String -> [String] splitString c [] = [] splitString c s = let ( item , rest ) = break ( == c ) s ( _ , next ) = break ( /= c ) rest in item : splitString c next computeUsage :: String -> Double computeUsage s = (1.0 - ((lineElements ...
Port the provided C++ code into Haskell while preserving the original functionality.
#include <algorithm> #include <chrono> #include <iostream> #include <vector> int ulam(int n) { std::vector<int> ulams{1, 2}; std::vector<int> sieve{1, 1}; for (int u = 2; ulams.size() < n; ) { sieve.resize(u + ulams[ulams.size() - 2], 0); for (int i = 0; i < ulams.size() - 1; ++i) ...
import Data.List ulam :: Integral i => Int -> i ulam 1 = 1 ulam 2 = 2 ulam n | n > 2 = ulams !! (n-1) ulams :: Integral n => [n] ulams = 1:2:(nexts [2,1]) nexts us = u: (nexts (u:us)) where n = length us [u] = head . filter isSingleton . group . sort $ [v | i <- [0 .. n-2], j ...
Convert this C++ snippet to Haskell and keep its semantics consistent.
#include <iostream> #include <iomanip> #include <string> #include <gmpxx.h> std::string smallest_six(unsigned int n) { mpz_class pow = 1; std::string goal = std::to_string(n); while (pow.get_str().find(goal) == std::string::npos) { pow *= 6; } return pow.get_str(); } int main() {...
import Data.List (find, isInfixOf) import Text.Printf (printf) smallest :: Integer -> Integer smallest n = d where Just d = find ((show n `isInfixOf`) . show) sixes sixes :: [Integer] sixes = iterate (* 6) 1 main :: IO () main = putStr $ [0 .. 21] >>= printf "%2d: %d\n" <*> smallest
Convert the following code from C++ to Haskell, ensuring the logic remains intact.
#include <iostream> using namespace std; bool steady(int n) { int mask = 1; for (int d = n; d != 0; d /= 10) mask *= 10; return (n * n) % mask == n; } int main() { for (int i = 1; i < 10000; i++) if (steady(i)) printf("%4d^2 = %8d\n", i, i * i); }
import Control.Monad (join) import Data.List (isSuffixOf) p :: Int -> Bool p = isSuffixOf . show <*> (show . join (*)) main :: IO () main = print $ takeWhile (< 10000) $ filter p [0 ..]
Port the provided C++ code into Haskell while preserving the original functionality.
#include <algorithm> #include <iostream> #include <iterator> #include <locale> #include <vector> #include "prime_sieve.hpp" const int limit1 = 1000000; const int limit2 = 10000000; class prime_info { public: explicit prime_info(int max) : max_print(max) {} void add_prime(int prime); void print(std::ostrea...
import Text.Printf (printf) import Data.Numbers.Primes (isPrime, primes) main = do printf "First 35 safe primes: %s\n" (show $ take 35 safe) printf "There are %d safe primes below 100,000.\n" (length $ takeWhile (<1000000) safe) printf "There are %d safe primes below 10,000,000.\n\n" (length $ takeWhile (<10000...
Transform the following C++ implementation into Haskell, maintaining the same output and logic.
#include <iostream> #include <string> #include <vector> #include <unordered_map> using tab_t = std::vector<std::vector<std::string>>; tab_t tab1 { {"27", "Jonah"} , {"18", "Alan"} , {"28", "Glory"} , {"18", "Popeye"} , {"28", "Alan"} }; tab_t tab2 { {"Jonah", "Whales"} , {"Jonah", "Spiders"} , {"Alan", "Ghosts"...
import qualified Data.HashTable.ST.Basic as H import Data.Hashable import Control.Monad.ST import Control.Monad import Data.STRef hashJoin :: (Eq k, Hashable k) => [t] -> (t -> k) -> [a] -> (a -> k) -> [(t, a)] hashJoin xs fx ys fy = runST $ do l <- newSTRef [] ht <- H.new forM_ ys $ \y -> H.insert ...
Write a version of this C++ function in Haskell with identical behavior.
#include <iostream> bool is_giuga(unsigned int n) { unsigned int m = n / 2; auto test_factor = [&m, n](unsigned int p) -> bool { if (m % p != 0) return true; m /= p; return m % p != 0 && (n / p - 1) % p == 0; }; if (!test_factor(3) || !test_factor(5)) return...
primeFactors :: Int -> [Int] primeFactors n = snd $ until ( (== 1) . fst ) step (n , [] ) where step :: (Int , [Int] ) -> (Int , [Int] ) step (n , li) = ( div n h , li ++ [h] ) where h :: Int h = head $ tail $ divisors n divisors :: Int -> [Int] divisors n = [d | d <- [1 .. n] , mod n d == 0] isGiu...
Ensure the translated Haskell code behaves exactly like the original C++ snippet.
#include <algorithm> #include <cstdlib> #include <fstream> #include <iomanip> #include <iostream> #include <string> #include <vector> int main() { std::vector<std::string> words; std::ifstream in("words.txt"); if (!in) { std::cerr << "Cannot open file words.txt.\n"; return EXIT_FAILURE; ...
import qualified Data.Set as S import qualified Data.Text as T import qualified Data.Text.IO as TIO anadromes :: [T.Text] -> [(T.Text, T.Text)] anadromes ws = let set = S.fromList $ map T.toLower ws in S.foldr (step set) [] set where step set w ps = let rev = T.reverse w in if...
Maintain the same structure and functionality when rewriting this code in Haskell.
#include <gmpxx.h> #include <algorithm> #include <cassert> #include <functional> #include <iostream> #include <vector> using big_int = mpz_class; const unsigned int small_primes[] = {2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, ...
primesTo100 = [2,3,5,7,11,13,17,19,23,29,31,37,41,43,47,53,59,61,67,71,73,79,83,89,97] find2km :: Integral a => a -> (Int,a) find2km n = f 0 n where f k m | r == 1 = (k,m) | otherwise = f (k+1) q where (q,r) = quotRem m 2 millerRabinPrimality :: Integer -> Integer -> Bool miller...
Convert this C++ snippet to Haskell and keep its semantics consistent.
#include <iostream> #include <ratio> #include <array> #include <algorithm> #include <random> typedef short int Digit; constexpr Digit nDigits{4}; constexpr Digit maximumDigit{9}; constexpr short int gameGoal{24}; typedef std::array<Digit, nDigits> digitSet; digitSet d; void printTrivialOperation(std::...
import Data.List import Data.Ratio import Control.Monad import System.Environment (getArgs) data Expr = Constant Rational | Expr :+ Expr | Expr :- Expr | Expr :* Expr | Expr :/ Expr deriving (Eq) ops = [(:+), (:-), (:*), (:/)] instance Show Expr where show (Constant x) = show $ numerator x ...
Convert this C++ block to Haskell, preserving its control flow and logic.
#include <iostream> #include <ratio> #include <array> #include <algorithm> #include <random> typedef short int Digit; constexpr Digit nDigits{4}; constexpr Digit maximumDigit{9}; constexpr short int gameGoal{24}; typedef std::array<Digit, nDigits> digitSet; digitSet d; void printTrivialOperation(std::...
import Data.List import Data.Ratio import Control.Monad import System.Environment (getArgs) data Expr = Constant Rational | Expr :+ Expr | Expr :- Expr | Expr :* Expr | Expr :/ Expr deriving (Eq) ops = [(:+), (:-), (:*), (:/)] instance Show Expr where show (Constant x) = show $ numerator x ...
Translate the given C++ code snippet into Haskell without altering its behavior.
#include <iostream> #include <list> int main () { std::list<int> numbers {1, 5, 7, 0, 3, 2}; numbers.insert(numbers.begin(), 9); numbers.insert(numbers.end(), 4); auto it = std::next(numbers.begin(), numbers.size() / 2); numbers.insert(it, 6); for(const auto& i: numbers) std::cout <...
import qualified Data.Map as M type NodeID = Maybe Rational data Node a = Node {vNode :: a, pNode, nNode :: NodeID} type DLList a = M.Map Rational (Node a) empty = M.empty singleton a = M.singleton 0 $ Node a Nothing Nothing fcons :: a -> DLList a -> DLList a fcons a list | M.null list = singleton a ...
Write the same algorithm in Haskell as shown in this C++ implementation.
#include <iostream> #include <stack> #include <string> #include <sstream> #include <vector> struct var { char name; bool value; }; std::vector<var> vars; template<typename T> T pop(std::stack<T> &s) { auto v = s.top(); s.pop(); return v; } bool is_operator(char c) { return c == '&' || c == '|...
import Control.Monad (mapM, foldM, forever) import Data.List (unwords, unlines, nub) import Data.Maybe (fromJust) truthTable expr = let tokens = words expr operators = ["&", "|", "!", "^", "=>"] variables = nub $ filter (not . (`elem` operators)) tokens table = zip variables <$> mapM (const [True,False...
Port the following code from C++ to Haskell with equivalent syntax and logic.
#include <iostream> #include <stack> #include <string> #include <sstream> #include <vector> struct var { char name; bool value; }; std::vector<var> vars; template<typename T> T pop(std::stack<T> &s) { auto v = s.top(); s.pop(); return v; } bool is_operator(char c) { return c == '&' || c == '|...
import Control.Monad (mapM, foldM, forever) import Data.List (unwords, unlines, nub) import Data.Maybe (fromJust) truthTable expr = let tokens = words expr operators = ["&", "|", "!", "^", "=>"] variables = nub $ filter (not . (`elem` operators)) tokens table = zip variables <$> mapM (const [True,False...
Write a version of this C++ function in Haskell with identical behavior.
#include <cassert> #include <functional> #include <iostream> #define _USE_MATH_DEFINES #include <math.h> enum RangeType { CLOSED, BOTH_OPEN, LEFT_OPEN, RIGHT_OPEN }; class RealSet { private: double low, high; double interval = 0.00001; std::function<bool(double)> predicate; public: R...
import Data.List import Data.Maybe data BracketType = OpenSub | ClosedSub deriving (Show, Enum, Eq, Ord) data RealInterval = RealInterval {left :: BracketType, right :: BracketType, lowerBound :: Double, upperBound :: Double} deriving (Eq) type RealSet = [RealInterval] posInf = 1.0/0.0 :: Double negI...
Convert this C++ snippet to Haskell and keep its semantics consistent.
#include <cassert> #include <functional> #include <iostream> #define _USE_MATH_DEFINES #include <math.h> enum RangeType { CLOSED, BOTH_OPEN, LEFT_OPEN, RIGHT_OPEN }; class RealSet { private: double low, high; double interval = 0.00001; std::function<bool(double)> predicate; public: R...
import Data.List import Data.Maybe data BracketType = OpenSub | ClosedSub deriving (Show, Enum, Eq, Ord) data RealInterval = RealInterval {left :: BracketType, right :: BracketType, lowerBound :: Double, upperBound :: Double} deriving (Eq) type RealSet = [RealInterval] posInf = 1.0/0.0 :: Double negI...
Port the provided C++ code into Haskell while preserving the original functionality.
#include <algorithm> #include <iostream> #include <string> #include <array> #include <vector> template<typename T> T unique(T&& src) { T retval(std::move(src)); std::sort(retval.begin(), retval.end(), std::less<typename T::value_type>()); retval.erase(std::unique(retval.begin(), retval.end()), retval.end()...
import Data.Char (isLetter, toLower) import Data.Function (on) import Data.List (groupBy, nub, sort, sortBy) puzzle :: [String] -> [((String, String), (String, String))] puzzle states = concatMap ((filter isValid . pairs) . map snd) ( filter ((> 1) . length) $ groupBy ((==) `on` fst) $ ...
Keep all operations the same but rewrite the snippet in Haskell.
#include <iostream> #include <sstream> #include <vector> uint64_t ipow(uint64_t base, uint64_t exp) { uint64_t result = 1; while (exp) { if (exp & 1) { result *= base; } exp >>= 1; base *= base; } return result; } int main() { using namespace std; v...
import Data.List (isInfixOf) import Data.Char (intToDigit) isSuperd :: (Show a, Integral a) => a -> a -> Bool isSuperd p n = (replicate <*> intToDigit) (fromIntegral p) `isInfixOf` show (p * n ^ p) findSuperd :: (Show a, Integral a) => a -> [a] findSuperd p = filter (isSuperd p) [1 ..] main :: IO () main = mapM_...
Port the following code from C++ to Haskell with equivalent syntax and logic.
#include <iostream> #include <sstream> #include <vector> uint64_t ipow(uint64_t base, uint64_t exp) { uint64_t result = 1; while (exp) { if (exp & 1) { result *= base; } exp >>= 1; base *= base; } return result; } int main() { using namespace std; v...
import Data.List (isInfixOf) import Data.Char (intToDigit) isSuperd :: (Show a, Integral a) => a -> a -> Bool isSuperd p n = (replicate <*> intToDigit) (fromIntegral p) `isInfixOf` show (p * n ^ p) findSuperd :: (Show a, Integral a) => a -> [a] findSuperd p = filter (isSuperd p) [1 ..] main :: IO () main = mapM_...
Translate the given C++ code snippet into Haskell without altering its behavior.
#include <iostream> #include <map> #include <cmath> int pRec(int n) { static std::map<int,int> memo; auto it = memo.find(n); if (it != memo.end()) return it->second; if (n <= 2) memo[n] = 1; else memo[n] = pRec(n-2) + pRec(n-3); return memo[n]; } int pFloor(int n) { long const double ...
pRec = map (\(a,_,_) -> a) $ iterate (\(a,b,c) -> (b,c,a+b)) (1,1,1) pSelfRef = 1 : 1 : 1 : zipWith (+) pSelfRef (tail pSelfRef) pFloor = map f [0..] where f n = floor $ p**fromInteger (pred n) / s + 0.5 p = 1.324717957244746025960908854 s = 1.0453567932525329623 lSystem = ...
Maintain the same structure and functionality when rewriting this code in Haskell.
#include <iostream> #include <cmath> #include <optional> #include <vector> using namespace std; template <typename T> auto operator>>(const optional<T>& monad, auto f) { if(!monad.has_value()) { return optional<remove_reference_t<decltype(*f(*monad))>>(); } return f(*monad)...
main = do print $ Just 3 >>= (return . (*2)) >>= (return . (+1)) print $ Nothing >>= (return . (*2)) >>= (return . (+1))
Ensure the translated Haskell code behaves exactly like the original C++ snippet.
#include <iostream> #include <vector> using namespace std; template <typename T> auto operator>>(const vector<T>& monad, auto f) { vector<remove_reference_t<decltype(f(monad.front()).front())>> result; for(auto& item : monad) { const auto r = f(item); resul...
main = print $ [3,4,5] >>= (return . (+1)) >>= (return . (*2))
Rewrite the snippet below in Haskell so it works the same as the original C++ code.
#include <fstream> #include <iostream> #include <unordered_map> #include <vector> struct Textonym_Checker { private: int total; int elements; int textonyms; int max_found; std::vector<std::string> max_strings; std::unordered_map<std::string, std::vector<std::string>> values; int get_mappin...
import Data.Char (toUpper) import Data.Function (on) import Data.List (groupBy, sortBy) import Data.Maybe (fromMaybe, isJust, isNothing) toKey :: Char -> Maybe Char toKey ch | ch < 'A' = Nothing | ch < 'D' = Just '2' | ch < 'G' = Just '3' | ch < 'J' = Just '4' | ch < 'M' = Just '5' | ch < 'P' = Just '6' ...
Generate a Haskell translation of this C++ snippet without changing its computational steps.
#include <iostream> auto Zero = [](auto){ return [](auto x){ return x; }; }; auto True = [](auto a){ return [=](auto){ return a; }; }; auto False = [](auto){ return [](auto b){ return b; }; }; auto Successor(auto a) { return [=](auto f) { return [=](auto x) { return a(f)(f(x)); }; ...
import Unsafe.Coerce ( unsafeCoerce ) type Church a = (a -> a) -> a -> a churchZero :: Church a churchZero = const id churchOne :: Church a churchOne = id succChurch :: Church a -> Church a succChurch = (<*>) (.) addChurch :: Church a -> Church a -> Church a addChurch = (<*>). fmap (.) multChurch :: Church a -...
Change the following C++ code into Haskell without altering its purpose.
#include <iostream> auto Zero = [](auto){ return [](auto x){ return x; }; }; auto True = [](auto a){ return [=](auto){ return a; }; }; auto False = [](auto){ return [](auto b){ return b; }; }; auto Successor(auto a) { return [=](auto f) { return [=](auto x) { return a(f)(f(x)); }; ...
import Unsafe.Coerce ( unsafeCoerce ) type Church a = (a -> a) -> a -> a churchZero :: Church a churchZero = const id churchOne :: Church a churchOne = id succChurch :: Church a -> Church a succChurch = (<*>) (.) addChurch :: Church a -> Church a -> Church a addChurch = (<*>). fmap (.) multChurch :: Church a -...
Translate this program into Haskell but keep the logic exactly as in C++.
#include <cstdint> #include <iomanip> #include <iostream> #include <sstream> class ipv4_cidr { public: ipv4_cidr() {} ipv4_cidr(std::uint32_t address, unsigned int mask_length) : address_(address), mask_length_(mask_length) {} std::uint32_t address() const { return address_; } unsi...
import Control.Monad (guard) import Data.Bits ((.|.), (.&.), complement, shiftL, shiftR, zeroBits) import Data.Maybe (listToMaybe) import Data.Word (Word32, Word8) import Text.ParserCombinators.ReadP (ReadP, char, readP_to_S) import Text.Printf (printf) import Text.Read.Lex (readDecP) data CIDR = CIDR Word32 Word8 ...
Write the same code in Haskell as shown below in C++.
#include <cstdint> #include <iomanip> #include <iostream> #include <sstream> class ipv4_cidr { public: ipv4_cidr() {} ipv4_cidr(std::uint32_t address, unsigned int mask_length) : address_(address), mask_length_(mask_length) {} std::uint32_t address() const { return address_; } unsi...
import Control.Monad (guard) import Data.Bits ((.|.), (.&.), complement, shiftL, shiftR, zeroBits) import Data.Maybe (listToMaybe) import Data.Word (Word32, Word8) import Text.ParserCombinators.ReadP (ReadP, char, readP_to_S) import Text.Printf (printf) import Text.Read.Lex (readDecP) data CIDR = CIDR Word32 Word8 ...
Convert this C++ snippet to Haskell and keep its semantics consistent.
#include <cstdint> #include <iostream> #include <sstream> #include <gmpxx.h> typedef mpz_class integer; bool is_probably_prime(const integer& n) { return mpz_probab_prime_p(n.get_mpz_t(), 25) != 0; } bool is_prime(unsigned int n) { if (n < 2) return false; if (n % 2 == 0) return n == 2; ...
import Data.List (scanl1, elemIndices, nub) primes :: [Integer] primes = 2 : filter isPrime [3,5 ..] isPrime :: Integer -> Bool isPrime = isPrime_ primes where isPrime_ :: [Integer] -> Integer -> Bool isPrime_ (p:ps) n | p * p > n = True | n `mod` p == 0 = False | otherwise = isPrime_ ps n...
Rewrite the snippet below in Haskell so it works the same as the original C++ code.
#include <boost/multiprecision/gmp.hpp> #include <iostream> using namespace boost::multiprecision; mpz_int p(uint n, uint p) { mpz_int r = 1; mpz_int k = n - p; while (n > k) r *= n--; return r; } mpz_int c(uint n, uint k) { mpz_int r = p(n, k); while (k) r /= k--; return ...
perm :: Integer -> Integer -> Integer perm n k = product [n-k+1..n] comb :: Integer -> Integer -> Integer comb n k = perm n k `div` product [1..k] main :: IO () main = do let showBig maxlen b = let st = show b stlen = length st in if stlen < maxlen then st e...
Maintain the same structure and functionality when rewriting this code in Haskell.
#include <gmpxx.h> #include <chrono> using namespace std; using namespace chrono; void agm(mpf_class& rop1, mpf_class& rop2, const mpf_class& op1, const mpf_class& op2) { rop1 = (op1 + op2) / 2; rop2 = op1 * op2; mpf_sqrt(rop2.get_mpf_t(), rop2.get_mpf_t()); } int main(void) { auto st = ste...
import Prelude hiding (pi) import Data.Number.MPFR hiding (sqrt, pi, div) import Data.Number.MPFR.Instances.Near () digitBits :: (Integral a, Num a) => a -> a digitBits n = (n + 1) `div` 2 * 8 pi :: Integer -> MPFR pi digits = let eps = fromString ("1e-" ++ show digits) (fromInteger $ digitBits digit...
Rewrite the snippet below in Haskell so it works the same as the original C++ code.
#include <gmpxx.h> #include <chrono> using namespace std; using namespace chrono; void agm(mpf_class& rop1, mpf_class& rop2, const mpf_class& op1, const mpf_class& op2) { rop1 = (op1 + op2) / 2; rop2 = op1 * op2; mpf_sqrt(rop2.get_mpf_t(), rop2.get_mpf_t()); } int main(void) { auto st = ste...
import Prelude hiding (pi) import Data.Number.MPFR hiding (sqrt, pi, div) import Data.Number.MPFR.Instances.Near () digitBits :: (Integral a, Num a) => a -> a digitBits n = (n + 1) `div` 2 * 8 pi :: Integer -> MPFR pi digits = let eps = fromString ("1e-" ++ show digits) (fromInteger $ digitBits digit...
Convert this C++ block to Haskell, preserving its control flow and logic.
#include <iomanip> #include <iostream> #include <list> using namespace std; void sieve(int limit, list<int> &primes) { bool *c = new bool[limit + 1]; for (int i = 0; i <= limit; i++) c[i] = false; int p = 3, n = 0; int p2 = p * p; while (p2 <= limit) { for (int i = p2; i <= limit; i += 2 * p) ...
import Data.List (elemIndex) longPrimesUpTo :: Int -> [Int] longPrimesUpTo n = filter isLongPrime $ takeWhile (< n) primes where sieve (p : xs) = p : sieve [x | x <- xs, x `mod` p /= 0] primes = sieve [2 ..] isLongPrime n = found where cycles = take n (iterate ((`mod` n) . (10 *)) 1) ...
Write the same algorithm in Haskell as shown in this C++ implementation.
using System; class Program { static int l; static int[] gp(int n) { var c = new bool[n]; var r = new int[(int)(1.28 * n)]; l = 0; r[l++] = 2; r[l++] = 3; int j, d, lim = (int)Math.Sqrt(n); for (int i = 9; i < n; i += 6) c[i] = true; for (j = 5, d = 4; j < lim; j += (d = 6 - ...
import Control.Arrow ((&&&)) import Data.List (scanl1, foldl1') getNthPrimorial :: Int -> Integer getNthPrimorial n = foldl1' (*) (take n primes) primes :: [Integer] primes = 2 : filter isPrime [3,5..] isPrime :: Integer -> Bool isPrime = isPrime_ primes where isPrime_ :: [Integer] -> Integer -> Bool isPri...
Can you help me rewrite this code in Haskell instead of C++, keeping it the same logically?
#include <iostream> #include <optional> #include <vector> #include <string> #include <sstream> #include <boost/multiprecision/cpp_int.hpp> typedef boost::multiprecision::cpp_int integer; struct fraction { fraction(const integer& n, const integer& d) : numerator(n), denominator(d) {} integer numerator; int...
import Data.Ratio (Ratio, (%), denominator, numerator) egyptianFraction :: Integral a => Ratio a -> [Ratio a] egyptianFraction n | n < 0 = map negate (egyptianFraction (-n)) | n == 0 = [] | x == 1 = [n] | x > y = (x `div` y % 1) : egyptianFraction (x `mod` y % y) | otherwise = (1 % r) : egyptianFraction ((-y...
Preserve the algorithm and functionality while converting the code from C++ to Haskell.
#include <iostream> #include <optional> #include <vector> #include <string> #include <sstream> #include <boost/multiprecision/cpp_int.hpp> typedef boost::multiprecision::cpp_int integer; struct fraction { fraction(const integer& n, const integer& d) : numerator(n), denominator(d) {} integer numerator; int...
import Data.Ratio (Ratio, (%), denominator, numerator) egyptianFraction :: Integral a => Ratio a -> [Ratio a] egyptianFraction n | n < 0 = map negate (egyptianFraction (-n)) | n == 0 = [] | x == 1 = [n] | x > y = (x `div` y % 1) : egyptianFraction (x `mod` y % y) | otherwise = (1 % r) : egyptianFraction ((-y...
Rewrite the snippet below in Haskell so it works the same as the original C++ code.
#include <iostream> #include <iomanip> #include <cmath> namespace Rosetta { template <int N> class GaussLegendreQuadrature { public: enum {eDEGREE = N}; template <typename Function> double integrate(double a, double b, Function f) { double p = (b - a) / 2...
gaussLegendre n f a b = d*sum [ w x*f(m + d*x) | x <- roots ] where d = (b - a)/2 m = (b + a)/2 w x = 2/(1-x^2)/(legendreP' n x)^2 roots = map (findRoot (legendreP n) (legendreP' n) . x0) [1..n] x0 i = cos (pi*(i-1/4)/(n+1/2))
Write the same algorithm in Haskell as shown in this C++ implementation.
#include <algorithm> #include <array> #include <cmath> #include <iostream> #include <random> #include <vector> template<typename coordinate_type, size_t dimensions> class point { public: point(std::array<coordinate_type, dimensions> c) : coords_(c) {} point(std::initializer_list<coordinate_type> list) { ...
import System.Random import Data.List (sortBy, genericLength, minimumBy) import Data.Ord (comparing) type DimensionalAccessors a b = [a -> b] data Tree a = Node a (Tree a) (Tree a) | Empty instance Show a => Show (Tree a) where show Empty = "Empty" show (Node value left right) = "(" ++ show va...
Change the following C++ code into Haskell without altering its purpose.
#include <algorithm> #include <array> #include <cmath> #include <iostream> #include <random> #include <vector> template<typename coordinate_type, size_t dimensions> class point { public: point(std::array<coordinate_type, dimensions> c) : coords_(c) {} point(std::initializer_list<coordinate_type> list) { ...
import System.Random import Data.List (sortBy, genericLength, minimumBy) import Data.Ord (comparing) type DimensionalAccessors a b = [a -> b] data Tree a = Node a (Tree a) (Tree a) | Empty instance Show a => Show (Tree a) where show Empty = "Empty" show (Node value left right) = "(" ++ show va...
Convert this C++ snippet to Haskell and keep its semantics consistent.
#include <array> #include <iostream> #include <stack> #include <vector> const std::array<std::pair<int, int>, 4> DIRS = { std::make_pair(0, -1), std::make_pair(-1, 0), std::make_pair(0, 1), std::make_pair(1, 0), }; void printResult(const std::vector<std::vector<int>> &v) { for (auto &row : v) {...
import qualified Data.Vector.Unboxed.Mutable as V import Data.STRef import Control.Monad (forM_, when) import Control.Monad.ST dir :: [(Int, Int)] dir = [(1, 0), (-1, 0), (0, -1), (0, 1)] data Env = Env { w, h, len, count, ret :: !Int, next :: ![Int] } cutIt :: STRef s Env -> ST s () cutIt env = do e <- readSTRe...
Convert this C++ block to Haskell, preserving its control flow and logic.
#include <array> #include <iostream> #include <stack> #include <vector> const std::array<std::pair<int, int>, 4> DIRS = { std::make_pair(0, -1), std::make_pair(-1, 0), std::make_pair(0, 1), std::make_pair(1, 0), }; void printResult(const std::vector<std::vector<int>> &v) { for (auto &row : v) {...
import qualified Data.Vector.Unboxed.Mutable as V import Data.STRef import Control.Monad (forM_, when) import Control.Monad.ST dir :: [(Int, Int)] dir = [(1, 0), (-1, 0), (0, -1), (0, 1)] data Env = Env { w, h, len, count, ret :: !Int, next :: ![Int] } cutIt :: STRef s Env -> ST s () cutIt env = do e <- readSTRe...
Transform the following C++ implementation into Haskell, maintaining the same output and logic.
#include <iostream> #include <vector> #include <chrono> #include <climits> #include <cmath> using namespace std; vector <long long> primes{ 3, 5 }; int main() { cout.imbue(locale("")); const int cutOff = 200, bigUn = 100000, chunks = 50, little = bigUn / chunks; const char tn[] = " cuban prime"; ...
import Data.Numbers.Primes (isPrime) import Data.List (intercalate) import Data.List.Split (chunksOf) import Text.Printf (printf) cubans :: [Int] cubans = filter isPrime . map (\x -> (succ x ^ 3) - (x ^ 3)) $ [1 ..] main :: IO () main = do mapM_ (\row -> mapM_ (printf "%10s" . thousands) row >> printf "\n") $ rows ...
Port the following code from C++ to Haskell with equivalent syntax and logic.
#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...