Instruction
stringlengths
45
106
input_code
stringlengths
1
13.7k
output_code
stringlengths
1
13.7k
Preserve the algorithm and functionality while converting the code from Python to Haskell.
from itertools import product def replicateM(n): def rep(m): def go(x): return [[]] if 1 > x else ( liftA2List(lambda a, b: [a] + b)(m)(go(x - 1)) ) return go(n) return lambda m: rep(m) def main(): print( fTable(main.__doc__ ...
import Control.Monad (replicateM) main = mapM_ print (replicateM 2 [1,2,3])
Please provide an equivalent version of this Python code in Haskell.
import random def is_probable_prime(n,k): if n==0 or n==1: return False if n==2: return True if n % 2 == 0: return False s = 0 d = n-1 while True: quotient, remainder = divmod(d, 2) if remainder == 1: break s += 1 d = quo...
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...
Change the following Python code into Haskell without altering its purpose.
import pyttsx engine = pyttsx.init() engine.say("It was all a dream.") engine.runAndWait()
import System.Process (callProcess) say text = callProcess "espeak" [" main = say "This is an example of speech synthesis."
Ensure the translated Haskell code behaves exactly like the original Python snippet.
def builtinsort(x): x.sort() def partition(seq, pivot): low, middle, up = [], [], [] for x in seq: if x < pivot: low.append(x) elif x == pivot: middle.append(x) else: up.append(x) return low, middle, up import random def qsortranpart(seq): size = le...
import Data.Time.Clock import Data.List type Time = Integer type Sorter a = [a] -> [a] timed :: IO a -> IO (a, Time) timed prog = do t0 <- getCurrentTime x <- prog t1 <- x `seq` getCurrentTime return (x, ceiling $ 1000000 * diffUTCTime t1 t0) test :: [a] -> Sorter a -> IO [(Int, Time)] test set srt = mapM...
Write a version of this Python function in Haskell with identical behavior.
from __future__ import division, print_function from itertools import permutations, combinations, product, \ chain from pprint import pprint as pp from fractions import Fraction as F import random, ast, re import sys if sys.version_info[0] < 3: input = raw_input from ...
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 ...
Ensure the translated Haskell code behaves exactly like the original Python snippet.
from __future__ import division, print_function from itertools import permutations, combinations, product, \ chain from pprint import pprint as pp from fractions import Fraction as F import random, ast, re import sys if sys.version_info[0] < 3: input = raw_input from ...
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 ...
Rewrite this program in Haskell while keeping its functionality equivalent to the Python version.
from math import hypot, pi, cos, sin from PIL import Image def hough(im, ntx=460, mry=360): "Calculate Hough transform." pim = im.load() nimx, mimy = im.size mry = int(mry/2)*2 him = Image.new("L", (ntx, mry), 255) phim = him.load() rmax = hypot(nimx, mimy) dr = rmax / (mry/...
import Control.Monad (forM_, when) import Data.Array ((!)) import Data.Array.ST (newArray, writeArray, readArray, runSTArray) import qualified Data.Foldable as F (maximum) import System.Environment (getArgs, getProgName) import Codec.Picture (DynamicImage(ImageRGB8, ImageRGBA8), Image, PixelRGB8(PixelRGB8), ...
Generate a Haskell translation of this Python snippet without changing its computational steps.
environments = [{'cnt':0, 'seq':i+1} for i in range(12)] code = while any(env['seq'] > 1 for env in environments): for env in environments: exec(code, globals(), env) print() print('Counts') for env in environments: print('% 4d' % env['cnt'], end='') print()
hailstone n | n == 1 = 1 | even n = n `div` 2 | odd n = 3*n + 1
Produce a language-to-language conversion: from Python to Haskell, same semantics.
def legendre(a, p): return pow(a, (p - 1) // 2, p) def tonelli(n, p): assert legendre(n, p) == 1, "not a square (mod p)" q = p - 1 s = 0 while q % 2 == 0: q //= 2 s += 1 if s == 1: return pow(n, (p + 1) // 4, p) for z in range(2, p): if p - 1 == legendre(z, p...
import Data.List (genericTake, genericLength) import Data.Bits (shiftR) powMod :: Integer -> Integer -> Integer -> Integer powMod m b e = go b e 1 where go b e r | e == 0 = r | odd e = go ((b*b) `mod` m) (e `div` 2) ((r*b) `mod` m) | even e = go ((b*b) `mod` m) (e `div` 2) r legendre :: Inte...
Port the provided Python code into Haskell while preserving the original functionality.
def legendre(a, p): return pow(a, (p - 1) // 2, p) def tonelli(n, p): assert legendre(n, p) == 1, "not a square (mod p)" q = p - 1 s = 0 while q % 2 == 0: q //= 2 s += 1 if s == 1: return pow(n, (p + 1) // 4, p) for z in range(2, p): if p - 1 == legendre(z, p...
import Data.List (genericTake, genericLength) import Data.Bits (shiftR) powMod :: Integer -> Integer -> Integer -> Integer powMod m b e = go b e 1 where go b e r | e == 0 = r | odd e = go ((b*b) `mod` m) (e `div` 2) ((r*b) `mod` m) | even e = go ((b*b) `mod` m) (e `div` 2) r legendre :: Inte...
Generate an equivalent Haskell version of this Python code.
from collections import deque some_list = deque(["a", "b", "c"]) print(some_list) some_list.appendleft("Z") print(some_list) for value in reversed(some_list): print(value)
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 ...
Rewrite this program in Haskell while keeping its functionality equivalent to the Python version.
from itertools import product while True: bexp = input('\nBoolean expression: ') bexp = bexp.strip() if not bexp: print("\nThank you") break code = compile(bexp, '<string>', 'eval') names = code.co_names print('\n' + ' '.join(names), ':', bexp) for values in product(range(2)...
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...
Keep all operations the same but rewrite the snippet in Haskell.
from itertools import product while True: bexp = input('\nBoolean expression: ') bexp = bexp.strip() if not bexp: print("\nThank you") break code = compile(bexp, '<string>', 'eval') names = code.co_names print('\n' + ' '.join(names), ':', bexp) for values in product(range(2)...
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 provided Python code into Haskell while preserving the original functionality.
class Setr(): def __init__(self, lo, hi, includelo=True, includehi=False): self.eqn = "(%i<%sX<%s%i)" % (lo, '=' if includelo else '', '=' if includehi else '', hi) def __contains__(self, X...
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...
Produce a language-to-language conversion: from Python to Haskell, same semantics.
class Setr(): def __init__(self, lo, hi, includelo=True, includehi=False): self.eqn = "(%i<%sX<%s%i)" % (lo, '=' if includelo else '', '=' if includehi else '', hi) def __contains__(self, X...
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...
Write the same code in Haskell as shown below in Python.
from collections import defaultdict states = ["Alabama", "Alaska", "Arizona", "Arkansas", "California", "Colorado", "Connecticut", "Delaware", "Florida", "Georgia", "Hawaii", "Idaho", "Illinois", "Indiana", "Iowa", "Kansas", "Kentucky", "Louisiana", "Maine", "Maryland", "Massachusetts", "Michigan", "Minnesota", "Missi...
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) $ ...
Transform the following Python implementation into Haskell, maintaining the same output and logic.
from itertools import islice, count def superd(d): if d != int(d) or not 2 <= d <= 9: raise ValueError("argument must be integer from 2 to 9 inclusive") tofind = str(d) * d for n in count(2): if tofind in str(d * n ** d): yield n if __name__ == '__main__': for d in range(2,...
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_...
Change the following Python code into Haskell without altering its purpose.
from itertools import islice, count def superd(d): if d != int(d) or not 2 <= d <= 9: raise ValueError("argument must be integer from 2 to 9 inclusive") tofind = str(d) * d for n in count(2): if tofind in str(d * n ** d): yield n if __name__ == '__main__': for d in range(2,...
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_...
Please provide an equivalent version of this Python code in Haskell.
from math import floor from collections import deque from typing import Dict, Generator def padovan_r() -> Generator[int, None, None]: last = deque([1, 1, 1], 4) while True: last.append(last[-2] + last[-3]) yield last.popleft() _p, _s = 1.324717957244746025960908854, 1.0453567932525329623 de...
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 = ...
Translate the given Python code snippet into Haskell without altering its behavior.
from __future__ import annotations from typing import Any from typing import Callable from typing import Generic from typing import Optional from typing import TypeVar from typing import Union T = TypeVar("T") class Maybe(Generic[T]): def __init__(self, value: Union[Optional[T], Maybe[T]] = None): if ...
main = do print $ Just 3 >>= (return . (*2)) >>= (return . (+1)) print $ Nothing >>= (return . (*2)) >>= (return . (+1))
Generate an equivalent Haskell version of this Python code.
from __future__ import annotations from itertools import chain from typing import Any from typing import Callable from typing import Iterable from typing import List from typing import TypeVar T = TypeVar("T") class MList(List[T]): @classmethod def unit(cls, value: Iterable[T]) -> MList[T]: return...
main = print $ [3,4,5] >>= (return . (+1)) >>= (return . (*2))
Convert the following code from Python to Haskell, ensuring the logic remains intact.
from collections import defaultdict import urllib.request CH2NUM = {ch: str(num) for num, chars in enumerate('abc def ghi jkl mno pqrs tuv wxyz'.split(), 2) for ch in chars} URL = 'http://www.puzzlers.org/pub/wordlists/unixdict.txt' def getwords(url): return urllib.request.urlopen(url).read().decode("utf-8").lower(...
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' ...
Produce a functionally identical Haskell code for the snippet given in Python.
gridsize = (6, 4) minerange = (0.2, 0.6) try: raw_input except: raw_input = input import random from itertools import product from pprint import pprint as pp def gridandmines(gridsize=gridsize, minerange=minerange): xgrid, ygrid = gridsize minmines, maxmines = minerange minecount = xgri...
module MineSweeper ( Board , Cell(..) , CellState(..) , Pos , pos , coveredLens , coveredFlaggedLens , coveredMinedLens , xCoordLens , yCoordLens , emptyBoard , groupedByRows , displayCell , isLoss , isWin , exposeMines , openCell , flagCell , mineBoard , totalRows ...
Translate this program into Haskell but keep the logic exactly as in Python.
from itertools import repeat from functools import reduce def churchZero(): return lambda f: identity def churchSucc(cn): return lambda f: compose(f)(cn(f)) def churchAdd(m): return lambda n: lambda f: compose(m(f))(n(f)) def churchMult(m): return lambda n: compose(m)(n) ...
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 -...
Convert this Python block to Haskell, preserving its control flow and logic.
from itertools import repeat from functools import reduce def churchZero(): return lambda f: identity def churchSucc(cn): return lambda f: compose(f)(cn(f)) def churchAdd(m): return lambda n: lambda f: compose(m(f))(n(f)) def churchMult(m): return lambda n: compose(m)(n) ...
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 -...
Generate an equivalent Haskell version of this Python code.
>>> 3 3 >>> _*_, _**0.5 (9, 1.7320508075688772) >>>
Prelude> [1..10] [1,2,3,4,5,6,7,8,9,10] Prelude> map (^2) it [1,4,9,16,25,36,49,64,81,100]
Port the following code from Python to Haskell with equivalent syntax and logic.
>>> 3 3 >>> _*_, _**0.5 (9, 1.7320508075688772) >>>
Prelude> [1..10] [1,2,3,4,5,6,7,8,9,10] Prelude> map (^2) it [1,4,9,16,25,36,49,64,81,100]
Preserve the algorithm and functionality while converting the code from Python to Haskell.
import binascii import functools import hashlib digits58 = b'123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz' def b58(n): return b58(n//58) + digits58[n%58:n%58+1] if n else b'' def public_point_to_address(x, y): c = b'\x04' + binascii.unhexlify(x) + binascii.unhexlify(y) r = hashlib.new('ri...
import Numeric (showIntAtBase) import Data.List (unfoldr) import Data.Binary (Word8) import Crypto.Hash.SHA256 as S (hash) import Crypto.Hash.RIPEMD160 as R (hash) import Data.ByteString (unpack, pack) publicPointToAddress :: Integer -> Integer -> String publicPointToAddress x y = let toBytes x = reverse $ unfoldr ...
Rewrite this program in Haskell while keeping its functionality equivalent to the Python version.
import binascii import functools import hashlib digits58 = b'123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz' def b58(n): return b58(n//58) + digits58[n%58:n%58+1] if n else b'' def public_point_to_address(x, y): c = b'\x04' + binascii.unhexlify(x) + binascii.unhexlify(y) r = hashlib.new('ri...
import Numeric (showIntAtBase) import Data.List (unfoldr) import Data.Binary (Word8) import Crypto.Hash.SHA256 as S (hash) import Crypto.Hash.RIPEMD160 as R (hash) import Data.ByteString (unpack, pack) publicPointToAddress :: Integer -> Integer -> String publicPointToAddress x y = let toBytes x = reverse $ unfoldr ...
Convert this Python snippet to Haskell and keep its semantics consistent.
import sys from socket import inet_aton, inet_ntoa from struct import pack, unpack args = sys.argv[1:] if len(args) == 0: args = sys.stdin.readlines() for cidr in args: dotted, size_str = cidr.split('/') size = int(size_str) numeric = unpack('!I', inet_aton(dotted))[0] binary = f'{numeric: ...
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 ...
Transform the following Python implementation into Haskell, maintaining the same output and logic.
import sys from socket import inet_aton, inet_ntoa from struct import pack, unpack args = sys.argv[1:] if len(args) == 0: args = sys.stdin.readlines() for cidr in args: dotted, size_str = cidr.split('/') size = int(size_str) numeric = unpack('!I', inet_aton(dotted))[0] binary = f'{numeric: ...
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 Python snippet to Haskell and keep its semantics consistent.
import pyprimes def primorial_prime(_pmax=500): isprime = pyprimes.isprime n, primo = 0, 1 for prime in pyprimes.nprimes(_pmax): n, primo = n+1, primo * prime if isprime(primo-1) or isprime(primo+1): yield n if __name__ == '__main__': pyprimes.warn_probably = F...
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...
Translate the given Python code snippet into Haskell without altering its behavior.
from __future__ import print_function from scipy.misc import factorial as fact from scipy.misc import comb def perm(N, k, exact=0): return comb(N, k, exact) * fact(k, exact) exact=True print('Sample Perms 1..12') for N in range(1, 13): k = max(N-2, 1) print('%iP%i =' % (N, k), perm(N, k, exact), end=', '...
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...
Translate this program into Haskell but keep the logic exactly as in Python.
from decimal import * D = Decimal getcontext().prec = 100 a = n = D(1) g, z, half = 1 / D(2).sqrt(), D(0.25), D(0.5) for i in range(18): x = [(a + g) * half, (a * g).sqrt()] var = x[0] - a z -= var * var * n n += n a, g = x print(a * a / z)
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...
Write the same code in Haskell as shown below in Python.
from decimal import * D = Decimal getcontext().prec = 100 a = n = D(1) g, z, half = 1 / D(2).sqrt(), D(0.25), D(0.5) for i in range(18): x = [(a + g) * half, (a * g).sqrt()] var = x[0] - a z -= var * var * n n += n a, g = x print(a * a / z)
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 Python block to Haskell, preserving its control flow and logic.
from Xlib import X, display class Window: def __init__(self, display, msg): self.display = display self.msg = msg self.screen = self.display.screen() self.window = self.screen.root.create_window( 10, 10, 100, 100, 1, self.screen.root_depth, ...
import Graphics.X11.Xlib import Control.Concurrent (threadDelay) main = do display <- openDisplay "" let defScr = defaultScreen display rw <- rootWindow display defScr xwin <- createSimpleWindow display rw 0 0 400 200 1 (blackPixel display defScr) (whitePixel display defScr) setTextProper...
Translate the given Python code snippet into Haskell without altering its behavior.
def sieve(limit): primes = [] c = [False] * (limit + 1) p = 3 while True: p2 = p * p if p2 > limit: break for i in range(p2, limit, 2 * p): c[i] = True while True: p += 2 if not c[p]: break for i in range(3, limit, 2): if not c[i...
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) ...
Rewrite the snippet below in Haskell so it works the same as the original Python code.
from pyprimes import nprimes from functools import reduce primelist = list(nprimes(1000001)) def primorial(n): return reduce(int.__mul__, primelist[:n], 1) if __name__ == '__main__': print('First ten primorals:', [primorial(n) for n in range(10)]) for e in range(7): n = 10**e print('...
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...
Convert this Python snippet to Haskell and keep its semantics consistent.
from fractions import Fraction from math import ceil class Fr(Fraction): def __repr__(self): return '%s/%s' % (self.numerator, self.denominator) def ef(fr): ans = [] if fr >= 1: if fr.denominator == 1: return [[int(fr)], Fr(0, 1)] intfr = int(fr) ans, fr = [[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...
Write the same code in Haskell as shown below in Python.
from fractions import Fraction from math import ceil class Fr(Fraction): def __repr__(self): return '%s/%s' % (self.numerator, self.denominator) def ef(fr): ans = [] if fr >= 1: if fr.denominator == 1: return [[int(fr)], Fr(0, 1)] intfr = int(fr) ans, fr = [[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...
Keep all operations the same but rewrite the snippet in Haskell.
from numpy import * def Legendre(n,x): x=array(x) if (n==0): return x*0+1.0 elif (n==1): return x else: return ((2.0*n-1.0)*x*Legendre(n-1,x)-(n-1)*Legendre(n-2,x))/n def DLegendre(n,x): x=array(x) if (n==0): return x*0 elif (n==1): return x*0+1.0 else: return (n/(x**2-1.0))*(x*Legendre(n,x)...
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))
Port the following code from Python to Haskell with equivalent syntax and logic.
from random import seed, random from time import time from operator import itemgetter from collections import namedtuple from math import sqrt from copy import deepcopy def sqd(p1, p2): return sum((c1 - c2) ** 2 for c1, c2 in zip(p1, p2)) class KdNode(object): __slots__ = ("dom_elt", "split", "left", "right...
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 programming language of this snippet from Python to Haskell without modifying what it does.
from random import seed, random from time import time from operator import itemgetter from collections import namedtuple from math import sqrt from copy import deepcopy def sqd(p1, p2): return sum((c1 - c2) ** 2 for c1, c2 in zip(p1, p2)) class KdNode(object): __slots__ = ("dom_elt", "split", "left", "right...
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...
Preserve the algorithm and functionality while converting the code from Python to Haskell.
from PIL import Image if __name__=="__main__": im = Image.open("frog.png") im2 = im.quantize(16) im2.show()
import qualified Data.ByteString.Lazy as BS import qualified Data.Foldable as Fold import qualified Data.List as List import Data.Ord import qualified Data.Sequence as Seq import Data.Word import System.Environment import Codec.Picture import Codec.Picture.Types type Accessor = PixelRGB8 -> Pixel8 red, blue, green...
Translate the given Python code snippet into Haskell without altering its behavior.
def cut_it(h, w): dirs = ((1, 0), (-1, 0), (0, -1), (0, 1)) if h % 2: h, w = w, h if h % 2: return 0 if w == 1: return 1 count = 0 next = [w + 1, -w - 1, -1, 1] blen = (h + 1) * (w + 1) - 1 grid = [False] * (blen + 1) def walk(y, x, count): if not y or y == h or not x or x ...
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 Python implementation into Haskell, maintaining the same output and logic.
def cut_it(h, w): dirs = ((1, 0), (-1, 0), (0, -1), (0, 1)) if h % 2: h, w = w, h if h % 2: return 0 if w == 1: return 1 count = 0 next = [w + 1, -w - 1, -1, 1] blen = (h + 1) * (w + 1) - 1 grid = [False] * (blen + 1) def walk(y, x, count): if not y or y == h or not x or x ...
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 Python block to Haskell, preserving its control flow and logic.
import datetime import math primes = [ 3, 5 ] cutOff = 200 bigUn = 100_000 chunks = 50 little = bigUn / chunks tn = " cuban prime" print ("The first {:,}{}s:".format(cutOff, tn)) c = 0 showEach = True u = 0 v = 1 st = datetime.datetime.now() for i in range(1, int(math.pow(2,20))): found = False u += 6 v += u ...
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 ...
Write the same code in Haskell as shown below in Python.
from __future__ import division size(300, 260) background(255) x = floor(random(width)) y = floor(random(height)) for _ in range(30000): v = floor(random(3)) if v == 0: x = x / 2 y = y / 2 colour = color(0, 255, 0) elif v == 1: x = width / 2 + (width / 2 - x) / 2 ...
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...
Convert this Python snippet to Haskell and keep its semantics consistent.
from __future__ import division size(300, 260) background(255) x = floor(random(width)) y = floor(random(height)) for _ in range(30000): v = floor(random(3)) if v == 0: x = x / 2 y = y / 2 colour = color(0, 255, 0) elif v == 1: x = width / 2 + (width / 2 - x) / 2 ...
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...
Convert this Python block to Haskell, preserving its control flow and logic.
from collections import namedtuple from pprint import pprint as pp OpInfo = namedtuple('OpInfo', 'prec assoc') L, R = 'Left Right'.split() ops = { '^': OpInfo(prec=4, assoc=R), '*': OpInfo(prec=3, assoc=L), '/': OpInfo(prec=3, assoc=L), '+': OpInfo(prec=2, assoc=L), '-': OpInfo(prec=2, assoc=L), '(': OpInfo(pre...
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 <> [...
Rewrite the snippet below in Haskell so it works the same as the original Python code.
from __future__ import print_function import matplotlib.pyplot as plt class AStarGraph(object): def __init__(self): self.barriers = [] self.barriers.append([(2,4),(2,5),(2,6),(3,6),(4,6),(5,6),(5,5),(5,4),(5,3),(5,2),(4,2),(3,2)]) def heuristic(self, start, goal): D = 1 D2 = 1 dx = abs(start[0] -...
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) ...
Can you help me rewrite this code in Haskell instead of Python, keeping it the same logically?
from __future__ import print_function import matplotlib.pyplot as plt class AStarGraph(object): def __init__(self): self.barriers = [] self.barriers.append([(2,4),(2,5),(2,6),(3,6),(4,6),(5,6),(5,5),(5,4),(5,3),(5,2),(4,2),(3,2)]) def heuristic(self, start, goal): D = 1 D2 = 1 dx = abs(start[0] -...
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 the following code from Python to Haskell, ensuring the logic remains intact.
from itertools import izip def gen_row(w, s): def gen_seg(o, sp): if not o: return [[2] * sp] return [[2] * x + o[0] + tail for x in xrange(1, sp - len(o) + 2) for tail in gen_seg(o[1:], sp - x)] return [x[1:] for x in gen_seg([[1] * i for i in ...
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...
Convert the following code from Python to Haskell, ensuring the logic remains intact.
from itertools import izip def gen_row(w, s): def gen_seg(o, sp): if not o: return [[2] * sp] return [[2] * x + o[0] + tail for x in xrange(1, sp - len(o) + 2) for tail in gen_seg(o[1:], sp - x)] return [x[1:] for x in gen_seg([[1] * i for i in ...
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...
Write a version of this Python function in Haskell with identical behavior.
import mpmath as mp with mp.workdps(72): def integer_term(n): p = 532 * n * n + 126 * n + 9 return (p * 2**5 * mp.factorial(6 * n)) / (3 * mp.factorial(n)**6) def exponent_term(n): return -(mp.mpf("6.0") * n + 3) def nthterm(n): return integer_term(n) * mp.mpf("10.0")**ex...
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...
Produce a functionally identical Haskell code for the snippet given in Python.
import mpmath as mp with mp.workdps(72): def integer_term(n): p = 532 * n * n + 126 * n + 9 return (p * 2**5 * mp.factorial(6 * n)) / (3 * mp.factorial(n)**6) def exponent_term(n): return -(mp.mpf("6.0") * n + 3) def nthterm(n): return integer_term(n) * mp.mpf("10.0")**ex...
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...
Convert this Python block to Haskell, preserving its control flow and logic.
from __future__ import print_function def add_reverse(num, max_iter=1000): i, nums = 0, {num} while True: i, num = i+1, num + reverse_int(num) nums.add(num) if reverse_int(num) == num or i >= max_iter: break return nums def reverse_int(num): return int(str(num)...
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 (...
Translate this program into Haskell but keep the logic exactly as in Python.
from __future__ import print_function def add_reverse(num, max_iter=1000): i, nums = 0, {num} while True: i, num = i+1, num + reverse_int(num) nums.add(num) if reverse_int(num) == num or i >= max_iter: break return nums def reverse_int(num): return int(str(num)...
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 (...
Produce a language-to-language conversion: from Python to Haskell, same semantics.
import re from fractions import Fraction from pprint import pprint as pp equationtext = def parse_eqn(equationtext=equationtext): eqn_re = re.compile(r) found = eqn_re.findall(equationtext) machins, part = [], [] for lhs, sign, mult, numer, denom in eqn_re.findall(equationtext): if lhs and ...
import Data.Ratio import Data.List (foldl') tanPlus :: Fractional a => a -> a -> a tanPlus a b = (a + b) / (1 - a * b) tanEval :: (Integral a, Fractional b) => (a, b) -> b tanEval (0,_) = 0 tanEval (coef,f) | coef < 0 = -tanEval (-coef, f) | odd coef = tanPlus f $ tanEval (coef - 1, f) | otherwise = tanPlus a a ...
Preserve the algorithm and functionality while converting the code from Python to Haskell.
import re from fractions import Fraction from pprint import pprint as pp equationtext = def parse_eqn(equationtext=equationtext): eqn_re = re.compile(r) found = eqn_re.findall(equationtext) machins, part = [], [] for lhs, sign, mult, numer, denom in eqn_re.findall(equationtext): if lhs and ...
import Data.Ratio import Data.List (foldl') tanPlus :: Fractional a => a -> a -> a tanPlus a b = (a + b) / (1 - a * b) tanEval :: (Integral a, Fractional b) => (a, b) -> b tanEval (0,_) = 0 tanEval (coef,f) | coef < 0 = -tanEval (-coef, f) | odd coef = tanPlus f $ tanEval (coef - 1, f) | otherwise = tanPlus a a ...
Change the following Python code into Haskell without altering its purpose.
from spell_integer import spell_integer, SMALL, TENS, HUGE def int_from_words(num): words = num.replace(',','').replace(' and ', ' ').replace('-', ' ').split() if words[0] == 'minus': negmult = -1 words.pop(0) else: negmult = 1 small, total = 0, 0 for word in words: ...
import Data.Char (toLower) type Symbol = (String, Integer) type BinOp = (Integer -> Integer -> Integer) type State = [Transition] data Transition = Transition [Symbol] State BinOp | Illion State BinOp | Done type Words = [String] type Accumulator = Integer type TapeValue = (Accumulato...
Convert this Python block to Haskell, preserving its control flow and logic.
import random import collections INT_MASK = 0xFFFFFFFF class IsaacRandom(random.Random): def seed(self, seed=None): def mix(): init_state[0] ^= ((init_state[1]<<11)&INT_MASK); init_state[3] += init_state[0]; init_state[3] &= INT_MASK; init_state[1] += init_state[2]; init_...
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...
Port the provided Python code into Haskell while preserving the original functionality.
import random import collections INT_MASK = 0xFFFFFFFF class IsaacRandom(random.Random): def seed(self, seed=None): def mix(): init_state[0] ^= ((init_state[1]<<11)&INT_MASK); init_state[3] += init_state[0]; init_state[3] &= INT_MASK; init_state[1] += init_state[2]; init_...
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...
Produce a language-to-language conversion: from Python to Haskell, same semantics.
from math import factorial as fact from random import randrange from textwrap import wrap def identity_perm(n): return list(range(n)) def unranker1(n, r, pi): while n > 0: n1, (rdivn, rmodn) = n-1, divmod(r, n) pi[n1], pi[rmodn] = pi[rmodn], pi[n1] n = n1 r = rdivn return ...
fact :: Int -> Int fact n = product [1 .. n] rankPerm [] _ = [] rankPerm list n = c : rankPerm (a ++ b) r where (q, r) = n `divMod` fact (length list - 1) (a, c:b) = splitAt q list permRank [] = 0 permRank (x:xs) = length (filter (< x) xs) * fact (length xs) + permRank xs main :: IO () main = mapM_ f [0 ...
Convert this Python block to Haskell, preserving its control flow and logic.
from math import factorial as fact from random import randrange from textwrap import wrap def identity_perm(n): return list(range(n)) def unranker1(n, r, pi): while n > 0: n1, (rdivn, rmodn) = n-1, divmod(r, n) pi[n1], pi[rmodn] = pi[rmodn], pi[n1] n = n1 r = rdivn return ...
fact :: Int -> Int fact n = product [1 .. n] rankPerm [] _ = [] rankPerm list n = c : rankPerm (a ++ b) r where (q, r) = n `divMod` fact (length list - 1) (a, c:b) = splitAt q list permRank [] = 0 permRank (x:xs) = length (filter (< x) xs) * fact (length xs) + permRank xs main :: IO () main = mapM_ f [0 ...
Generate a Haskell translation of this Python snippet without changing its computational steps.
from math import log, modf, floor def p(l, n, pwr=2): l = int(abs(l)) digitcount = floor(log(l, 10)) log10pwr = log(pwr, 10) raised, found = -1, 0 while found < n: raised += 1 firstdigits = floor(10**(modf(log10pwr * raised)[0] + digitcount)) if firstdigits == l: ...
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...
Keep all operations the same but rewrite the snippet in Haskell.
from math import log, modf, floor def p(l, n, pwr=2): l = int(abs(l)) digitcount = floor(log(l, 10)) log10pwr = log(pwr, 10) raised, found = -1, 0 while found < n: raised += 1 firstdigits = floor(10**(modf(log10pwr * raised)[0] + digitcount)) if firstdigits == l: ...
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...
Translate the given Python code snippet into Haskell without altering its behavior.
computed = {} def sterling2(n, k): key = str(n) + "," + str(k) if key in computed.keys(): return computed[key] if n == k == 0: return 1 if (n > 0 and k == 0) or (n == 0 and k > 0): return 0 if n == k: return 1 if k > n: return 0 result = k * sterling2(n - 1, k) + sterling2(n - 1, k - 1) computed[key...
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 |...
Generate an equivalent Haskell version of this Python code.
computed = {} def sterling2(n, k): key = str(n) + "," + str(k) if key in computed.keys(): return computed[key] if n == k == 0: return 1 if (n > 0 and k == 0) or (n == 0 and k > 0): return 0 if n == k: return 1 if k > n: return 0 result = k * sterling2(n - 1, k) + sterling2(n - 1, k - 1) computed[key...
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 |...
Transform the following Python implementation into Haskell, maintaining the same output and logic.
import random def is_Prime(n): if n!=int(n): return False n=int(n) if n==0 or n==1 or n==4 or n==6 or n==8 or n==9: return False if n==2 or n==3 or n==5 or n==7: return True s = 0 d = n-1 while d%2==0: d>>=1 s+=1 assert(2**s * d == n-1...
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...
Port the provided Python code into Haskell while preserving the original functionality.
primes = [2, 3, 5, 7, 11, 13, 17, 19, 23] def isPrime(n): if n < 2: return False for i in primes: if n == i: return True if n % i == 0: return False if i * i > n: return True print "Oops,", n, " is too large" def init(): s = 24 w...
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...
Produce a functionally identical Haskell code for the snippet given in Python.
from itertools import combinations as cmb def isP(n): if n == 2: return True if n % 2 == 0: return False return all(n % x > 0 for x in range(3, int(n ** 0.5) + 1, 2)) def genP(n): p = [2] p.extend([x for x in range(3, n + 1, 2) if isP(x)]) return p data = [ (99809, 1), ...
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_ ...
Generate an equivalent Haskell version of this Python code.
import copy class Zeckendorf: def __init__(self, x='0'): q = 1 i = len(x) - 1 self.dLen = int(i / 2) self.dVal = 0 while i >= 0: self.dVal = self.dVal + (ord(x[i]) - ord('0')) * q q = q * 2 i = i -1 def a(self, n): i = n ...
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...
Convert this Python block to Haskell, preserving its control flow and logic.
computed = {} def sterling1(n, k): key = str(n) + "," + str(k) if key in computed.keys(): return computed[key] if n == k == 0: return 1 if n > 0 and k == 0: return 0 if k > n: return 0 result = sterling1(n - 1, k - 1) + (n - 1) * sterling1(n - 1, k) computed[key] = result return result print("Unsigne...
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 =...
Translate this program into Haskell but keep the logic exactly as in Python.
computed = {} def sterling1(n, k): key = str(n) + "," + str(k) if key in computed.keys(): return computed[key] if n == k == 0: return 1 if n > 0 and k == 0: return 0 if k > n: return 0 result = sterling1(n - 1, k - 1) + (n - 1) * sterling1(n - 1, k) computed[key] = result return result print("Unsigne...
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 =...
Port the following code from Python to Haskell with equivalent syntax and logic.
v1 = PVector(5, 7) v2 = PVector(2, 3) println('{} {} {} {}\n'.format( v1.x, v1.y, v1.mag(), v1.heading())) println(v1 + v2) println(v1 - v2) println(v1 * 11) println(v1 / 2) println('') println(v1.sub(v1)) println(v1.add(v2)) println(v1.mult(10)) println(v1.div(10))
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 = " +...
Rewrite the snippet below in Haskell so it works the same as the original Python code.
class Point: b = 7 def __init__(self, x=float('inf'), y=float('inf')): self.x = x self.y = y def copy(self): return Point(self.x, self.y) def is_zero(self): return self.x > 1e20 or self.x < -1e20 def neg(self): return Point(self.x, -self.y) def dbl(s...
import Data.Monoid import Control.Monad (guard) import Test.QuickCheck (quickCheck)
Maintain the same structure and functionality when rewriting this code in Haskell.
class Point: b = 7 def __init__(self, x=float('inf'), y=float('inf')): self.x = x self.y = y def copy(self): return Point(self.x, self.y) def is_zero(self): return self.x > 1e20 or self.x < -1e20 def neg(self): return Point(self.x, -self.y) def dbl(s...
import Data.Monoid import Control.Monad (guard) import Test.QuickCheck (quickCheck)
Write a version of this Python function in Haskell with identical behavior.
def bwt(s): assert "\002" not in s and "\003" not in s, "Input string cannot contain STX and ETX characters" s = "\002" + s + "\003" table = sorted(s[i:] + s[:i] for i in range(len(s))) last_column = [row[-1:] for row in table] return "".join(last_column) def ibwt(r): table =...
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...
Change the following Python code into Haskell without altering its purpose.
def bwt(s): assert "\002" not in s and "\003" not in s, "Input string cannot contain STX and ETX characters" s = "\002" + s + "\003" table = sorted(s[i:] + s[:i] for i in range(len(s))) last_column = [row[-1:] for row in table] return "".join(last_column) def ibwt(r): table =...
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...
Transform the following Python implementation into Haskell, maintaining the same output and logic.
from itertools import accumulate, chain, count, islice from fractions import Fraction def faulhaberTriangle(m): def go(rs, n): def f(x, y): return Fraction(n, x) * y xs = list(map(f, islice(count(2), m), rs)) return [Fraction(1 - sum(xs), 1)] + xs return list(accum...
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 ..]...
Ensure the translated Haskell code behaves exactly like the original Python snippet.
try: import psyco psyco.full() except ImportError: pass MAX_N = 300 BRANCH = 4 ra = [0] * MAX_N unrooted = [0] * MAX_N def tree(br, n, l, sum = 1, cnt = 1): global ra, unrooted, MAX_N, BRANCH for b in xrange(br + 1, BRANCH + 1): sum += n if sum >= MAX_N: return ...
a `nmul` n = map (*n) a a `ndiv` n = map (`div` n) a instance (Integral a) => Num [a] where (+) = zipWith (+) negate = map negate a * b = foldr f undefined b where f x z = (a `nmul` x) + (0 : z) abs _ = undefined signum _ = undefined fromInteger n = fromInteger n : repeat 0 repl a n = concatMap (: r...
Convert this Python block to Haskell, preserving its control flow and logic.
try: import psyco psyco.full() except ImportError: pass MAX_N = 300 BRANCH = 4 ra = [0] * MAX_N unrooted = [0] * MAX_N def tree(br, n, l, sum = 1, cnt = 1): global ra, unrooted, MAX_N, BRANCH for b in xrange(br + 1, BRANCH + 1): sum += n if sum >= MAX_N: return ...
a `nmul` n = map (*n) a a `ndiv` n = map (`div` n) a instance (Integral a) => Num [a] where (+) = zipWith (+) negate = map negate a * b = foldr f undefined b where f x z = (a `nmul` x) + (0 : z) abs _ = undefined signum _ = undefined fromInteger n = fromInteger n : repeat 0 repl a n = concatMap (: r...
Transform the following Python implementation into Haskell, maintaining the same output and logic.
from fractions import Fraction def nextu(a): n = len(a) a.append(1) for i in range(n - 1, 0, -1): a[i] = i * a[i] + a[i - 1] return a def nextv(a): n = len(a) - 1 b = [(1 - n) * x for x in a] b.append(1) for i in range(n): b[i + 1] += a[i] return b def sumpol(n): ...
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 ...
Produce a functionally identical Haskell code for the snippet given in Python.
Import-Module ActiveDirectory $searchData = "user name" $searchBase = "DC=example,DC=com" get-aduser -Filter((DistinguishedName -eq $searchdata) -or (UserPrincipalName -eq $searchdata) -or (SamAccountName -eq $searchdata)) -SearchBase $searchBase
module Main (main) where import Data.Foldable (for_) import qualified Data.Text.Encoding as Text (encodeUtf8) import Ldap.Client (Attr(..), Filter(..)) import qualified Ldap.Client as Ldap (Dn(..), Host(..), search, with, typesOnly) main :: IO () main = do entries <- Ldap.with (Ldap.Plain "l...
Translate the given Python code snippet into Haskell without altering its behavior.
def isPrime(n): if n < 2: return False if n % 2 == 0: return n == 2 if n % 3 == 0: return n == 3 d = 5 while d * d <= n: if n % d == 0: return False d += 2 if n % d == 0: return False d += 4 return True def genera...
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...
Change the programming language of this snippet from Python to Haskell without modifying what it does.
def bags(n,cache={}): if not n: return [(0, "")] upto = sum([bags(x) for x in range(n-1, 0, -1)], []) return [(c+1, '('+s+')') for c,s in bagchain((0, ""), n-1, upto)] def bagchain(x, n, bb, start=0): if not n: return [x] out = [] for i in range(start, len(bb)): c,s = bb[i] if c <= n: out += bagchain((x[0]...
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 _ = [""]...
Write a version of this Python function in Haskell with identical behavior.
from elementary_cellular_automaton import eca, eca_wrap def rule30bytes(lencells=100): cells = '1' + '0' * (lencells - 1) gen = eca(cells, 30) while True: yield int(''.join(next(gen)[0] for i in range(8)), 2) if __name__ == '__main__': print([b for i,b in zip(range(10), rule30bytes())])
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
Keep all operations the same but rewrite the snippet in Haskell.
from __future__ import print_function def lgen(even=False, nmax=1000000): start = 2 if even else 1 n, lst = 1, list(range(start, nmax + 1, 2)) lenlst = len(lst) yield lst[0] while n < lenlst and lst[n] < lenlst: yield lst[n] n, lst = n + 1, [j for i,j in enumerate(lst, 1) if i % lst...
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 "======================|========...
Generate an equivalent Haskell version of this Python code.
import math import re def inv(c): denom = c.real * c.real + c.imag * c.imag return complex(c.real / denom, -c.imag / denom) class QuaterImaginary: twoI = complex(0, 2) invTwoI = inv(twoI) def __init__(self, str): if not re.match("^[0123.]+$", str) or str.count('.') > 1: raise ...
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...
Generate a Haskell translation of this Python snippet without changing its computational steps.
from __future__ import division import matplotlib.pyplot as plt import random mean, stddev, size = 50, 4, 100000 data = [random.gauss(mean, stddev) for c in range(size)] mn = sum(data) / size sd = (sum(x*x for x in data) / size - (sum(data) / size) ** 2) ** 0.5 print("Sample mean = %g; Stddev = %g; max = %g;...
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 following Python code into Haskell without altering its purpose.
def getA004290(n): if n < 2: return 1 arr = [[0 for _ in range(n)] for _ in range(n)] arr[0][0] = 1 arr[0][1] = 1 m = 0 while True: m += 1 if arr[m - 1][-10 ** m % n] == 1: break arr[m][0] = 1 for k in range(1, n): arr[m][k] = max([...
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...
Can you help me rewrite this code in Haskell instead of Python, keeping it the same logically?
import math from sys import stdout LOG_10 = 2.302585092994 def build_oms(s): if s % 2 == 0: s += 1 q = [[0 for j in range(s)] for i in range(s)] p = 1 i = s // 2 j = 0 while p <= (s * s): q[i][j] = p ti = i + 1 if ti >= s: ti = 0 tj = j - 1 if ...
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 functionally identical Haskell code for the snippet given in Python.
from itertools import chain, count, islice, repeat from functools import reduce from math import sqrt from time import time def weirds(): def go(n): ds = descPropDivs(n) d = sum(ds) - n return [n] if 0 < d and not hasSum(d, ds) else [] return concatMap(go)(count(1)) def hasS...
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 =...
Translate this program into Haskell but keep the logic exactly as in Python.
def validate(diagram): rawlines = diagram.splitlines() lines = [] for line in rawlines: if line != '': lines.append(line) if len(lines) == 0: print('diagram has no non-empty lines!') return None width = len(line...
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 ...
Rewrite this program in Haskell while keeping its functionality equivalent to the Python version.
def divisors(n): divs = [1] for ii in range(2, int(n ** 0.5) + 3): if n % ii == 0: divs.append(ii) divs.append(int(n / ii)) divs.append(n) return list(set(divs)) def is_prime(n): return len(divisors(n)) == 2 def primes(): ii = 1 while True: ii += 1...
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 = ...
Produce a functionally identical Haskell code for the snippet given in Python.
def prepend(n, seq): return [n] + seq def check_seq(pos, seq, n, min_len): if pos > min_len or seq[0] > n: return min_len, 0 if seq[0] == n: return pos, 1 if pos < min_len: return try_perm(0, pos, seq, n, min_len) return min_len, 0 def try_perm(i, pos, seq, n, min_len): ...
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 Python snippet.
states = { 'ready':{ 'prompt' : 'Machine ready: (d)eposit, or (q)uit?', 'responses' : ['d','q']}, 'waiting':{ 'prompt' : 'Machine waiting: (s)elect, or (r)efund?', 'responses' : ['s','r']}, 'dispense' : { 'prompt'...
import System.Exit import Data.Maybe import Control.Monad import Data.List import System.IO type Name = String type Sequence = String type State = String data Trigger = Trigger { name :: Name , tseq :: Sequence } deriving (Eq) instance Show Trigger where show (Trigger name tseq) = name ++ "(...
Write a version of this Python function in Haskell with identical behavior.
from array import array from collections import deque import psyco data = [] nrows = 0 px = py = 0 sdata = "" ddata = "" def init(board): global data, nrows, sdata, ddata, px, py data = filter(None, board.splitlines()) nrows = max(len(r) for r in data) maps = {' ':' ', '.': '.', '@':' ', ' mapd =...
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 ...
Please provide an equivalent version of this Python code in Haskell.
from sympy import divisors from sympy.combinatorics.subsets import Subset def isZumkeller(n): d = divisors(n) s = sum(d) if not s % 2 and max(d) <= s/2: for x in range(1, 2**len(d)): if sum(Subset.unrank_binary(x, d).subset) == s/2: return True return False def ...
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 ...