Instruction
stringlengths
45
106
input_code
stringlengths
1
13.7k
output_code
stringlengths
1
13.7k
Transform the following Python implementation into Haskell, maintaining the same output and logic.
fact = [1] for n in range(1, 12): fact.append(fact[n-1] * n) for b in range(9, 12+1): print(f"The factorions for base {b} are:") for i in range(1, 1500000): fact_sum = 0 j = i while j > 0: d = j % b fact_sum += fact[d] j = j//b if fact_su...
import Text.Printf (printf) import Data.List (unfoldr) import Control.Monad (guard) factorion :: Int -> Int -> Bool factorion b n = f b n == n where f b = sum . map (product . enumFromTo 1) . unfoldr (\x -> guard (x > 0) >> pure (x `mod` b, x `div` b)) main :: IO () main = mapM_ (uncurry (printf "Factorions for ba...
Produce a language-to-language conversion: from Python to Haskell, same semantics.
def factorize(n): assert(isinstance(n, int)) if n < 0: n = -n if n < 2: return k = 0 while 0 == n%2: k += 1 n //= 2 if 0 < k: yield (2,k) p = 3 while p*p <= n: k = 0 while 0 == n%p: k += 1 n //...
import Data.List.Split (chunksOf) divisors :: Integral a => a -> [a] divisors n = ((<>) <*> (rest . reverse . fmap (quot n))) $ filter ((0 ==) . rem n) [1 .. root] where root = (floor . sqrt . fromIntegral) n rest | n == root * root = tail | otherwise = id main :: IO () main = mapM_ ...
Port the provided Python code into Haskell while preserving the original functionality.
def factorize(n): assert(isinstance(n, int)) if n < 0: n = -n if n < 2: return k = 0 while 0 == n%2: k += 1 n //= 2 if 0 < k: yield (2,k) p = 3 while p*p <= n: k = 0 while 0 == n%p: k += 1 n //...
import Data.List.Split (chunksOf) divisors :: Integral a => a -> [a] divisors n = ((<>) <*> (rest . reverse . fmap (quot n))) $ filter ((0 ==) . rem n) [1 .. root] where root = (floor . sqrt . fromIntegral) n rest | n == root * root = tail | otherwise = id main :: IO () main = mapM_ ...
Translate this program into Haskell but keep the logic exactly as in Python.
def _insort_right(a, x, q): lo, hi = 0, len(a) while lo < hi: mid = (lo+hi)//2 q += 1 less = input(f"{q:2}: IS {x:>6} LESS-THAN {a[mid]:>6} ? y/n: ").strip().lower() == 'y' if less: hi = mid else: lo = mid+1 a.insert(lo, x) return q def order(items): or...
import Control.Monad import Control.Monad.ListM (sortByM, insertByM, partitionM, minimumByM) import Data.Bool (bool) import Data.Monoid import Data.List isortM, msortM, tsortM :: Monad m => (a -> a -> m Ordering) -> [a] -> m [a] msortM = sortByM isortM cmp = foldM (flip (insertByM cmp)) [] tsortM cmp = go whe...
Convert this Python snippet to Haskell and keep its semantics consistent.
def factors(x): factors = [] i = 2 s = int(x ** 0.5) while i < s: if x % i == 0: factors.append(i) x = int(x / i) s = int(x ** 0.5) i += 1 factors.append(x) return factors print("First 10 Fermat numbers:") for i in range(10): fermat = 2 **...
import Data.Numbers.Primes (primeFactors) import Data.Bool (bool) fermat :: Integer -> Integer fermat = succ . (2 ^) . (2 ^) fermats :: [Integer] fermats = fermat <$> [0 ..] main :: IO () main = mapM_ putStrLn [ fTable "First 10 Fermats:" show show fermat [0 .. 9] , fTable "Factors of first 7:...
Produce a functionally identical Haskell code for the snippet given in Python.
from itertools import zip_longest def beadsort(l): return list(map(sum, zip_longest(*[[1] * e for e in l], fillvalue=0))) print(beadsort([5,3,1,7,4,1,1]))
import Data.List beadSort :: [Int] -> [Int] beadSort = map sum. transpose. transpose. map (flip replicate 1)
Convert the following code from Python to Haskell, ensuring the logic remains intact.
def CastOut(Base=10, Start=1, End=999999): ran = [y for y in range(Base-1) if y%(Base-1) == (y*y)%(Base-1)] x,y = divmod(Start, Base-1) while True: for n in ran: k = (Base-1)*x + n if k < Start: continue if k > End: return yield k x += 1 for V in CastOut(Base=1...
co9 n | n <= 8 = n | otherwise = co9 $ sum $ filter (/= 9) $ digits 10 n task2 = filter (\n -> co9 n == co9 (n ^ 2)) [1 .. 100] task3 k = filter (\n -> n `mod` k == n ^ 2 `mod` k) [1 .. 100]
Change the following Python code into Haskell without altering its purpose.
def CastOut(Base=10, Start=1, End=999999): ran = [y for y in range(Base-1) if y%(Base-1) == (y*y)%(Base-1)] x,y = divmod(Start, Base-1) while True: for n in ran: k = (Base-1)*x + n if k < Start: continue if k > End: return yield k x += 1 for V in CastOut(Base=1...
co9 n | n <= 8 = n | otherwise = co9 $ sum $ filter (/= 9) $ digits 10 n task2 = filter (\n -> co9 n == co9 (n ^ 2)) [1 .. 100] task3 k = filter (\n -> n `mod` k == n ^ 2 `mod` k) [1 .. 100]
Translate the given Python code snippet into Haskell without altering its behavior.
import argparse from argparse import Namespace import datetime import shlex def parse_args(): 'Set up, parse, and return arguments' parser = argparse.ArgumentParser(epilog=globals()['__doc__']) parser.add_argument('command', choices='add pl plc pa'.split(), help=) par...
import Control.Monad.State import Data.List (sortBy, nub) import System.Environment (getArgs, getProgName) import System.Directory (doesFileExist) import System.IO (openFile, hGetContents, hClose, IOMode(..), Handle, hPutStrLn) data Date = Date Integer Int Int deriving (Show, Read, Eq, Ord) data Item = Item ...
Convert this Python snippet to Haskell and keep its semantics consistent.
def factorize(n): assert(isinstance(n, int)) if n < 0: n = -n if n < 2: return k = 0 while 0 == n%2: k += 1 n //= 2 if 0 < k: yield (2,k) p = 3 while p*p <= n: k = 0 while 0 == n%p: k += 1 n //...
tau :: Integral a => a -> a tau n | n <= 0 = error "Not a positive integer" tau n = go 0 (1, 1) where yo i = (i, i * i) go r (i, ii) | n < ii = r | n == ii = r + 1 | 0 == mod n i = go (r + 2) (yo $ i + 1) | otherwise = go r (yo $ i + 1) main = print $ map tau [1..100]
Produce a language-to-language conversion: from Python to Haskell, same semantics.
def factorize(n): assert(isinstance(n, int)) if n < 0: n = -n if n < 2: return k = 0 while 0 == n%2: k += 1 n //= 2 if 0 < k: yield (2,k) p = 3 while p*p <= n: k = 0 while 0 == n%p: k += 1 n //...
tau :: Integral a => a -> a tau n | n <= 0 = error "Not a positive integer" tau n = go 0 (1, 1) where yo i = (i, i * i) go r (i, ii) | n < ii = r | n == ii = r + 1 | 0 == mod n i = go (r + 2) (yo $ i + 1) | otherwise = go r (yo $ i + 1) main = print $ map tau [1..100]
Generate a Haskell translation of this Python snippet without changing its computational steps.
def isPrime(n) : if (n < 2) : return False for i in range(2, n + 1) : if (i * i <= n and n % i == 0) : return False return True def mobius(N) : if (N == 1) : return 1 p = 0 for i in range(1, N + 1) : if...
import Data.List (intercalate) import Data.List.Split (chunksOf) import Data.Vector.Unboxed (toList) import Math.NumberTheory.ArithmeticFunctions.Moebius (Moebius(..), sieveBlockMoebius) import System.Environment (getArgs, getProgName) import System.IO (hPutStrLn, s...
Generate an equivalent Haskell version of this Python code.
def Gcd(v1, v2): a, b = v1, v2 if (a < b): a, b = v2, v1 r = 1 while (r != 0): r = a % b if (r != 0): a = b b = r return b a = [1, 2] n = 3 while (n < 50): gcd1 = Gcd(n, a[-1]) gcd2 = Gcd(n, a[-2]) if (gcd1 == 1 a...
import Data.List (find, transpose, unfoldr) import Data.List.Split (chunksOf) import qualified Data.Set as S coprimeTriples :: Integral a => [a] coprimeTriples = [1, 2] <> unfoldr go (S.fromList [1, 2], (1, 2)) where go (seen, (a, b)) = Just (c, (S.insert c seen, (b, c))) where Ju...
Generate a Haskell translation of this Python snippet without changing its computational steps.
def Gcd(v1, v2): a, b = v1, v2 if (a < b): a, b = v2, v1 r = 1 while (r != 0): r = a % b if (r != 0): a = b b = r return b a = [1, 2] n = 3 while (n < 50): gcd1 = Gcd(n, a[-1]) gcd2 = Gcd(n, a[-2]) if (gcd1 == 1 a...
import Data.List (find, transpose, unfoldr) import Data.List.Split (chunksOf) import qualified Data.Set as S coprimeTriples :: Integral a => [a] coprimeTriples = [1, 2] <> unfoldr go (S.fromList [1, 2], (1, 2)) where go (seen, (a, b)) = Just (c, (S.insert c seen, (b, c))) where Ju...
Preserve the algorithm and functionality while converting the code from Python to Haskell.
def is_Curzon(n, k): r = k * n return pow(k, n, r + 1) == r for k in [2, 4, 6, 8, 10]: n, curzons = 1, [] while len(curzons) < 1000: if is_Curzon(n, k): curzons.append(n) n += 1 print(f'Curzon numbers with k = {k}:') for i, c in enumerate(curzons[:50]): print...
import Data.List.Split ( chunksOf ) isGeneralizedCurzon :: Integer -> Integer -> Bool isGeneralizedCurzon base n = mod ( base ^ n + 1 ) ( base * n + 1 ) == 0 solution :: Integer -> [Integer] solution base = take 50 $ filter (\i -> isGeneralizedCurzon base i ) [1..] printChunk :: [Integer] -> String printChunk chunk ...
Generate an equivalent Haskell version of this Python code.
def is_Curzon(n, k): r = k * n return pow(k, n, r + 1) == r for k in [2, 4, 6, 8, 10]: n, curzons = 1, [] while len(curzons) < 1000: if is_Curzon(n, k): curzons.append(n) n += 1 print(f'Curzon numbers with k = {k}:') for i, c in enumerate(curzons[:50]): print...
import Data.List.Split ( chunksOf ) isGeneralizedCurzon :: Integer -> Integer -> Bool isGeneralizedCurzon base n = mod ( base ^ n + 1 ) ( base * n + 1 ) == 0 solution :: Integer -> [Integer] solution base = take 50 $ filter (\i -> isGeneralizedCurzon base i ) [1..] printChunk :: [Integer] -> String printChunk chunk ...
Convert this Python snippet to Haskell and keep its semantics consistent.
def mertens(count): m = [None, 1] for n in range(2, count+1): m.append(1) for k in range(2, n+1): m[n] -= m[n//k] return m ms = mertens(1000) print("The first 99 Mertens numbers are:") print(" ", end=' ') col = 1 for n in ms[1:100]: print("{:2d}".format(n), end='...
import Data.List.Split (chunksOf) import qualified Data.MemoCombinators as Memo import Math.NumberTheory.Primes (unPrime, factorise) import Text.Printf (printf) moebius :: Integer -> Int moebius = product . fmap m . factorise where m (p, e) | unPrime p =...
Write a version of this Python function in Haskell with identical behavior.
def product_of_divisors(n): assert(isinstance(n, int) and 0 < n) ans = i = j = 1 while i*i <= n: if 0 == n%i: ans *= i j = n//i if j != i: ans *= j i += 1 return ans if __name__ == "__main__": print([product_of_divisors(n) for ...
import Data.List.Split (chunksOf) divisors :: Integral a => a -> [a] divisors n = ((<>) <*> (rest . reverse . fmap (quot n))) $ filter ((0 ==) . rem n) [1 .. root] where root = (floor . sqrt . fromIntegral) n rest | n == root * root = tail | otherwise = id main :: IO () main = mapM_ ...
Write a version of this Python function in Haskell with identical behavior.
def product_of_divisors(n): assert(isinstance(n, int) and 0 < n) ans = i = j = 1 while i*i <= n: if 0 == n%i: ans *= i j = n//i if j != i: ans *= j i += 1 return ans if __name__ == "__main__": print([product_of_divisors(n) for ...
import Data.List.Split (chunksOf) divisors :: Integral a => a -> [a] divisors n = ((<>) <*> (rest . reverse . fmap (quot n))) $ filter ((0 ==) . rem n) [1 .. root] where root = (floor . sqrt . fromIntegral) n rest | n == root * root = tail | otherwise = id main :: IO () main = mapM_ ...
Translate the given Python code snippet into Haskell without altering its behavior.
import random class Card(object): suits = ("Clubs","Hearts","Spades","Diamonds") pips = ("2","3","4","5","6","7","8","9","10","Jack","Queen","King","Ace") def __init__(self, pip,suit): self.pip=pip self.suit=suit def __str__(self): return "%s %s"%(self.pip,self.suit) class De...
import System.Random data Pip = Two | Three | Four | Five | Six | Seven | Eight | Nine | Ten | Jack | Queen | King | Ace deriving (Ord, Enum, Bounded, Eq, Show) data Suit = Diamonds | Spades | Hearts | Clubs deriving (Ord, Enum, Bounded, Eq, Show) type Card = (Pip, Suit) fullRange :: (Bounded a, En...
Write the same algorithm in Haskell as shown in this Python implementation.
from math import gcd def coprime(a, b): return 1 == gcd(a, b) def main(): print([ xy for xy in [ (21, 15), (17, 23), (36, 12), (18, 29), (60, 15) ] if coprime(*xy) ]) if __name__ == '__main__': main()
coprime :: Integral a => a -> a -> Bool coprime a b = 1 == gcd a b main :: IO () main = print $ filter ((1 ==) . uncurry gcd) [ (21, 15), (17, 23), (36, 12), (18, 29), (60, 15) ]
Generate a Haskell translation of this Python snippet without changing its computational steps.
from math import gcd def coprime(a, b): return 1 == gcd(a, b) def main(): print([ xy for xy in [ (21, 15), (17, 23), (36, 12), (18, 29), (60, 15) ] if coprime(*xy) ]) if __name__ == '__main__': main()
coprime :: Integral a => a -> a -> Bool coprime a b = 1 == gcd a b main :: IO () main = print $ filter ((1 ==) . uncurry gcd) [ (21, 15), (17, 23), (36, 12), (18, 29), (60, 15) ]
Convert this Python block to Haskell, preserving its control flow and logic.
from math import gcd from functools import lru_cache from itertools import islice, count @lru_cache(maxsize=None) def φ(n): return sum(1 for k in range(1, n + 1) if gcd(n, k) == 1) def perfect_totient(): for n0 in count(1): parts, n = 0, n0 while n != 1: n = φ(n) parts...
perfectTotients :: [Int] perfectTotients = filter ((==) <*> (succ . sum . tail . takeWhile (1 /=) . iterate φ)) [2 ..] φ :: Int -> Int φ = memoize (\n -> length (filter ((1 ==) . gcd n) [1 .. n])) memoize :: (Int -> a) -> (Int -> a) memoize f = (!!) (f <$> [0 ..]) main :: IO () main = print $ take 20 perfectTotien...
Write the same algorithm in Haskell as shown in this Python implementation.
from math import gcd from functools import lru_cache from itertools import islice, count @lru_cache(maxsize=None) def φ(n): return sum(1 for k in range(1, n + 1) if gcd(n, k) == 1) def perfect_totient(): for n0 in count(1): parts, n = 0, n0 while n != 1: n = φ(n) parts...
perfectTotients :: [Int] perfectTotients = filter ((==) <*> (succ . sum . tail . takeWhile (1 /=) . iterate φ)) [2 ..] φ :: Int -> Int φ = memoize (\n -> length (filter ((1 ==) . gcd n) [1 .. n])) memoize :: (Int -> a) -> (Int -> a) memoize f = (!!) (f <$> [0 ..]) main :: IO () main = print $ take 20 perfectTotien...
Can you help me rewrite this code in Haskell instead of Python, keeping it the same logically?
from math import (comb, factorial) def lah(n, k): if k == 1: return factorial(n) if k == n: return 1 if k > n: return 0 if k < 1 or n < 1: return 0 return comb(n, k) * factorial(n - 1) // factorial(k - 1) def main(): print("Unsigned Lah numbe...
import Text.Printf (printf) import Control.Monad (when) factorial :: Integral n => n -> n factorial 0 = 1 factorial n = product [1..n] lah :: Integral n => n -> n -> n lah n k | k == 1 = factorial n | k == n = 1 | k > n = 0 | k < 1 || n < 1 = 0 | otherwise = f n `div` f k `div` factorial (n - k) wh...
Rewrite the snippet below in Haskell so it works the same as the original Python code.
from math import (comb, factorial) def lah(n, k): if k == 1: return factorial(n) if k == n: return 1 if k > n: return 0 if k < 1 or n < 1: return 0 return comb(n, k) * factorial(n - 1) // factorial(k - 1) def main(): print("Unsigned Lah numbe...
import Text.Printf (printf) import Control.Monad (when) factorial :: Integral n => n -> n factorial 0 = 1 factorial n = product [1..n] lah :: Integral n => n -> n -> n lah n k | k == 1 = factorial n | k == n = 1 | k > n = 0 | k < 1 || n < 1 = 0 | otherwise = f n `div` f k `div` factorial (n - k) wh...
Ensure the translated Haskell code behaves exactly like the original Python snippet.
def two_sum(arr, num): i = 0 j = len(arr) - 1 while i < j: if arr[i] + arr[j] == num: return (i, j) if arr[i] + arr[j] < num: i += 1 else: j -= 1 return None numbers = [0, 2, 11, 19, 90] print(two_sum(numbers, 21)) print(two_sum(numbers, 25))...
twoSum::(Num a,Ord a) => a -> [a] -> [Int] twoSum num list = sol ls (reverse ls) where ls = zip list [0..] sol [] _ = [] sol _ [] = [] sol xs@((x,i):us) ys@((y,j):vs) = ans where s = x + y ans | s == num = [i,j] | j <= i = [] | s < num = sol (dropWhile ((<num).(+y).fst) us) y...
Generate an equivalent Haskell version of this Python code.
def two_sum(arr, num): i = 0 j = len(arr) - 1 while i < j: if arr[i] + arr[j] == num: return (i, j) if arr[i] + arr[j] < num: i += 1 else: j -= 1 return None numbers = [0, 2, 11, 19, 90] print(two_sum(numbers, 21)) print(two_sum(numbers, 25))...
twoSum::(Num a,Ord a) => a -> [a] -> [Int] twoSum num list = sol ls (reverse ls) where ls = zip list [0..] sol [] _ = [] sol _ [] = [] sol xs@((x,i):us) ys@((y,j):vs) = ans where s = x + y ans | s == num = [i,j] | j <= i = [] | s < num = sol (dropWhile ((<num).(+y).fst) us) y...
Change the programming language of this snippet from Python to Haskell without modifying what it does.
import sys if "UTF-8" in sys.stdout.encoding: print("△") else: raise Exception("Terminal can't handle UTF-8")
import System.Environment import Data.List import Data.Char import Data.Maybe main = do x <- mapM lookupEnv ["LANG", "LC_ALL", "LC_CTYPE"] if any (isInfixOf "UTF". map toUpper) $ catMaybes x then putStrLn "UTF supported: \x25b3" else putStrLn "UTF not supported"
Convert this Python block to Haskell, preserving its control flow and logic.
import sys if "UTF-8" in sys.stdout.encoding: print("△") else: raise Exception("Terminal can't handle UTF-8")
import System.Environment import Data.List import Data.Char import Data.Maybe main = do x <- mapM lookupEnv ["LANG", "LC_ALL", "LC_CTYPE"] if any (isInfixOf "UTF". map toUpper) $ catMaybes x then putStrLn "UTF supported: \x25b3" else putStrLn "UTF not supported"
Rewrite this program in Haskell while keeping its functionality equivalent to the Python version.
from itertools import count, islice def primes(_cache=[2, 3]): yield from _cache for n in count(_cache[-1]+2, 2): if isprime(n): _cache.append(n) yield n def isprime(n, _seen={0: False, 1: False}): def _isprime(n): for p in primes(): if p*p > n: ...
import Control.Lens ((.~), ix, (&)) import Data.Numbers.Primes (isPrime) import Data.List (find, intercalate) import Data.Char (intToDigit) import Data.Maybe (mapMaybe) import Data.List.Split (chunksOf) import Text.Printf (printf) isUnprimable :: Int -> Bool isUnprimable = all (not . isPrime) . swapdigits swapdigits ...
Produce a language-to-language conversion: from Python to Haskell, same semantics.
def tau(n): assert(isinstance(n, int) and 0 < n) ans, i, j = 0, 1, 1 while i*i <= n: if 0 == n%i: ans += 1 j = n//i if j != i: ans += 1 i += 1 return ans def is_tau_number(n): assert(isinstance(n, int)) if n <= 0: retur...
tau :: Integral a => a -> a tau n | n <= 0 = error "Not a positive integer" tau n = go 0 (1, 1) where yo i = (i, i * i) go r (i, ii) | n < ii = r | n == ii = r + 1 | 0 == mod n i = go (r + 2) (yo $ i + 1) | otherwise = go r (yo $ i + 1) isTau :: Integral a => a -> Bool isTau...
Translate the given Python code snippet into Haskell without altering its behavior.
from itertools import takewhile def primesWithGivenDigitSum(below, n): return list( takewhile( lambda x: below > x, ( x for x in primes() if n == sum(int(c) for c in str(x)) ) ) ) def main(): matches = pri...
import Data.Bifunctor (second) import Data.List (replicate) import Data.List.Split (chunksOf) import Data.Numbers.Primes (primes) matchingPrimes :: [Int] matchingPrimes = takeWhile (< 5000) [n | n <- primes, 25 == decimalDigitSum n] decimalDigitSum :: Int -> Int decimalDigitSum n = snd $ until ...
Rewrite the snippet below in Haskell so it works the same as the original Python code.
from itertools import takewhile def primesWithGivenDigitSum(below, n): return list( takewhile( lambda x: below > x, ( x for x in primes() if n == sum(int(c) for c in str(x)) ) ) ) def main(): matches = pri...
import Data.Bifunctor (second) import Data.List (replicate) import Data.List.Split (chunksOf) import Data.Numbers.Primes (primes) matchingPrimes :: [Int] matchingPrimes = takeWhile (< 5000) [n | n <- primes, 25 == decimalDigitSum n] decimalDigitSum :: Int -> Int decimalDigitSum n = snd $ until ...
Can you help me rewrite this code in Haskell instead of Python, keeping it the same logically?
from collections import deque def prime_digits_sum(r): q = deque([(r, 0)]) while q: r, n = q.popleft() for d in 2, 3, 5, 7: if d >= r: if d == r: yield n + d break q.append((r - d, (n + d) * 10)) print(*prime_digits_sum(13))
import Data.List.Split (chunksOf) import Data.List (intercalate, transpose, unfoldr) import Text.Printf primeDigitsNumsSummingToN :: Int -> [Int] primeDigitsNumsSummingToN n = concat $ unfoldr go (return <$> primeDigits) where primeDigits = [2, 3, 5, 7] go :: [[Int]] -> Maybe ([Int], [[Int]]) go xs ...
Can you help me rewrite this code in Haskell instead of Python, keeping it the same logically?
from collections import deque def prime_digits_sum(r): q = deque([(r, 0)]) while q: r, n = q.popleft() for d in 2, 3, 5, 7: if d >= r: if d == r: yield n + d break q.append((r - d, (n + d) * 10)) print(*prime_digits_sum(13))
import Data.List.Split (chunksOf) import Data.List (intercalate, transpose, unfoldr) import Text.Printf primeDigitsNumsSummingToN :: Int -> [Int] primeDigitsNumsSummingToN n = concat $ unfoldr go (return <$> primeDigits) where primeDigits = [2, 3, 5, 7] go :: [[Int]] -> Maybe ([Int], [[Int]]) go xs ...
Rewrite the snippet below in Haskell so it works the same as the original Python code.
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 Math.NumberTheory.Primes (Prime, unPrime, nextPrime) import Math.NumberTheory.Primes.Testing (isPrime, millerRabinV) import Text.Printf (printf) rotated :: [Integer] -> [Integer] rotated xs | any (< head xs) xs = [] | otherwise = map asNum $ take (pred $ length xs) $ rotate xs where rotate [] =...
Rewrite this program in Haskell while keeping its functionality equivalent to the Python version.
def isPrime(v): if v <= 1: return False if v < 4: return True if v % 2 == 0: return False if v < 9: return True if v % 3 == 0: return False else: r = round(pow(v,0.5)) f = 5 while f <= r: if v % f == 0 or v % (f + 2) == 0: return False f += 6 return ...
primes = 2 : sieve [3,5..] where sieve (x:xs) = x : sieve (filter (\y -> y `mod` x /= 0) xs) frobenius = zipWith (\a b -> a*b - a - b) primes (tail primes)
Convert this Python block to Haskell, preserving its control flow and logic.
def isPrime(v): if v <= 1: return False if v < 4: return True if v % 2 == 0: return False if v < 9: return True if v % 3 == 0: return False else: r = round(pow(v,0.5)) f = 5 while f <= r: if v % f == 0 or v % (f + 2) == 0: return False f += 6 return ...
primes = 2 : sieve [3,5..] where sieve (x:xs) = x : sieve (filter (\y -> y `mod` x /= 0) xs) frobenius = zipWith (\a b -> a*b - a - b) primes (tail primes)
Produce a language-to-language conversion: from Python to Haskell, same semantics.
from itertools import permutations in_order = lambda s: all(x <= s[i+1] for i,x in enumerate(s[:-1])) perm_sort = lambda s: (p for p in permutations(s) if in_order(p)).next()
import Control.Monad permutationSort l = head [p | p <- permute l, sorted p] sorted (e1 : e2 : r) = e1 <= e2 && sorted (e2 : r) sorted _ = True permute = foldM (flip insert) [] insert e [] = return [e] insert e l@(h : t) = return (e : l) `mplus` do { t' <- ...
Change the programming language of this snippet from Python to Haskell without modifying what it does.
def root(a, b): if b < 2: return b a1 = a - 1 c = 1 d = (a1 * c + b // (c ** a1)) // a e = (a1 * d + b // (d ** a1)) // a while c not in (d, e): c, d, e = d, e, (a1 * e + b // (e ** a1)) // a return min(d, e) print("First 2,001 digits of the square root of two:\n{}".format(...
root :: Integer -> Integer -> Integer root a b = findAns $ iterate (\x -> (a1 * x + b `div` (x ^ a1)) `div` a) 1 where a1 = a - 1 findAns (x:xs@(y:z:_)) | x == y || x == z = min y z | otherwise = findAns xs main :: IO () main = do print $ root 3 8 print $ root 3 9 print $ root 2 (2 * 100 ^ ...
Write a version of this Python function in Haskell with identical behavior.
def root(a, b): if b < 2: return b a1 = a - 1 c = 1 d = (a1 * c + b // (c ** a1)) // a e = (a1 * d + b // (d ** a1)) // a while c not in (d, e): c, d, e = d, e, (a1 * e + b // (e ** a1)) // a return min(d, e) print("First 2,001 digits of the square root of two:\n{}".format(...
root :: Integer -> Integer -> Integer root a b = findAns $ iterate (\x -> (a1 * x + b `div` (x ^ a1)) `div` a) 1 where a1 = a - 1 findAns (x:xs@(y:z:_)) | x == y || x == z = min y z | otherwise = findAns xs main :: IO () main = do print $ root 3 8 print $ root 3 9 print $ root 2 (2 * 100 ^ ...
Maintain the same structure and functionality when rewriting this code in Haskell.
from sympy.ntheory.generate import primorial from sympy.ntheory import isprime def fortunate_number(n): i = 3 primorial_ = primorial(n) while True: if isprime(primorial_ + i): return i i += 2 fortunate_numbers = set() for i in range(1, 76): fortunate_numbers....
import Data.Numbers.Primes (primes) import Math.NumberTheory.Primes.Testing (isPrime) import Data.List (nub) primorials :: [Integer] primorials = 1 : scanl1 (*) primes nextPrime :: Integer -> Integer nextPrime n | even n = head $ dropWhile (not . isPrime) [n+1, n+3..] | even n = nextPrime (n+1) fortunateNumbers ...
Can you help me rewrite this code in Haskell instead of Python, keeping it the same logically?
def meaning_of_life(): return 42 if __name__ == "__main__": print("Main: The meaning of life is %s" % meaning_of_life())
#!/usr/bin/env runhaskell module ScriptedMain where meaningOfLife :: Int meaningOfLife = 42 main :: IO () main = putStrLn $ "Main: The meaning of life is " ++ show meaningOfLife
Rewrite this program in Haskell while keeping its functionality equivalent to the Python version.
def meaning_of_life(): return 42 if __name__ == "__main__": print("Main: The meaning of life is %s" % meaning_of_life())
#!/usr/bin/env runhaskell module ScriptedMain where meaningOfLife :: Int meaningOfLife = 42 main :: IO () main = putStrLn $ "Main: The meaning of life is " ++ show meaningOfLife
Convert the following code from Python to Haskell, ensuring the logic remains intact.
import ast class CallCountingVisitor(ast.NodeVisitor): def __init__(self): self.calls = {} def visit_Call(self, node): if isinstance(node.func, ast.Name): fun_name = node.func.id call_count = self.calls.get(fun_name, 0) self.calls[fun_name] = call_count + 1...
import Language.Haskell.Parser (parseModule) import Data.List.Split (splitOn) import Data.List (nub, sortOn, elemIndices) findApps src = freq $ concat [apps, comps] where ast = show $ parseModule src apps = extract <$> splitApp ast comps = extract <$> concat (splitComp <$> splitInfix ast) splitApp = ...
Maintain the same structure and functionality when rewriting this code in Haskell.
nicePrimes( s, e ) = { local( m ); forprime( p = s, e, m = p; \\ while( m > 9, \\ m == p mod 9 m = sumdigits( m ) ); \\ if( isprime( m ), print1( p, " " ) ) ); }
import Data.Char ( digitToInt ) isPrime :: Int -> Bool isPrime n |n == 2 = True |n == 1 = False |otherwise = null $ filter (\i -> mod n i == 0 ) [2 .. root] where root :: Int root = floor $ sqrt $ fromIntegral n digitsum :: Int -> Int digitsum n = sum $ map digitToInt $ show n findSumn :: I...
Port the following code from Python to Haskell with equivalent syntax and logic.
nicePrimes( s, e ) = { local( m ); forprime( p = s, e, m = p; \\ while( m > 9, \\ m == p mod 9 m = sumdigits( m ) ); \\ if( isprime( m ), print1( p, " " ) ) ); }
import Data.Char ( digitToInt ) isPrime :: Int -> Bool isPrime n |n == 2 = True |n == 1 = False |otherwise = null $ filter (\i -> mod n i == 0 ) [2 .. root] where root :: Int root = floor $ sqrt $ fromIntegral n digitsum :: Int -> Int digitsum n = sum $ map digitToInt $ show n findSumn :: I...
Produce a language-to-language conversion: from Python to Haskell, same semantics.
import sys import calendar year = 2013 if len(sys.argv) > 1: try: year = int(sys.argv[-1]) except ValueError: pass for month in range(1, 13): last_sunday = max(week[-1] for week in calendar.monthcalendar(year, month)) print('{}-{}-{:2}'.format(year, calendar.month_abbr[month], last_sun...
import Data.List (find, intercalate, transpose) import Data.Maybe (fromJust) import Data.Time.Calendar ( Day, addDays, fromGregorian, gregorianMonthLength, showGregorian, ) import Data.Time.Calendar.WeekDate (toWeekDate) lastSundayOfEachMonth = lastWeekDayDates 7 main :: IO () main = mapM_ ...
Generate a Haskell translation of this Python snippet without changing its computational steps.
import sys import calendar year = 2013 if len(sys.argv) > 1: try: year = int(sys.argv[-1]) except ValueError: pass for month in range(1, 13): last_sunday = max(week[-1] for week in calendar.monthcalendar(year, month)) print('{}-{}-{:2}'.format(year, calendar.month_abbr[month], last_sun...
import Data.List (find, intercalate, transpose) import Data.Maybe (fromJust) import Data.Time.Calendar ( Day, addDays, fromGregorian, gregorianMonthLength, showGregorian, ) import Data.Time.Calendar.WeekDate (toWeekDate) lastSundayOfEachMonth = lastWeekDayDates 7 main :: IO () main = mapM_ ...
Translate this program into Haskell but keep the logic exactly as in Python.
from random import choice, shuffle from copy import deepcopy def rls(n): if n <= 0: return [] else: symbols = list(range(n)) square = _rls(symbols) return _shuffle_transpose_shuffle(square) def _shuffle_transpose_shuffle(matrix): square = deepcopy(matrix) shuffle(squar...
import Data.List (permutations, (\\)) latinSquare :: Eq a => [a] -> [a] -> [[a]] latinSquare [] [] = [] latinSquare c r | head r /= head c = [] | otherwise = reverse <$> foldl addRow firstRow perms where perms = tail $ fmap (fmap . (:) <*> (permutations . (r \\) . return)) ...
Produce a language-to-language conversion: from Python to Haskell, same semantics.
from itertools import chain, groupby from os.path import expanduser from functools import reduce def main(): print('\n'.join( concatMap(circularGroup)( anagrams(3)( lines(readFile('~/mitWords.txt')) ) ) )) def anagrams(n): ...
import Data.List (groupBy, intercalate, sort, sortBy) import qualified Data.Set as S import Data.Ord (comparing) import Data.Function (on) main :: IO () main = readFile "mitWords.txt" >>= (putStrLn . showGroups . circularWords . lines) circularWords :: [String] -> [String] circularWords ws = let lexicon = S.fromL...
Please provide an equivalent version of this Python code in Haskell.
from itertools import count, islice def _basechange_int(num, b): if num == 0: return [0] result = [] while num != 0: num, d = divmod(num, b) result.append(d) return result[::-1] def fairshare(b=2): for i in count(): yield sum(_basechange_int(i, b)) % b if __na...
import Data.Bool (bool) import Data.List (intercalate, unfoldr) import Data.Tuple (swap) thueMorse :: Int -> [Int] thueMorse base = baseDigitsSumModBase base <$> [0 ..] baseDigitsSumModBase :: Int -> Int -> Int baseDigitsSumModBase base n = mod ( sum $ unfoldr ( bool Nothing . ...
Change the following Python code into Haskell without altering its purpose.
from collections import deque from itertools import dropwhile, islice, takewhile from textwrap import wrap from typing import Iterable, Iterator Digits = str def esthetic_nums(base: int) -> Iterator[int]: queue: deque[tuple[int, int]] = deque() queue.extendleft((d, d) for d in range(1, base)) whi...
import Data.List (unfoldr, genericIndex) import Control.Monad (replicateM, foldM, mzero) isEsthetic b = all ((== 1) . abs) . differences . toBase b where differences lst = zipWith (-) lst (tail lst) esthetics_m b = do differences <- (\n -> replicateM n [-1, 1]) <$> [0..] firstDigit <- [1..b-1] dif...
Translate this program into Haskell but keep the logic exactly as in Python.
from operator import itemgetter DEBUG = False def spermutations(n): sign = 1 p = [[i, 0 if i == 0 else -1] for i in range(n)] if DEBUG: print ' yield tuple(pp[0] for pp in p), sign while any(pp[1] for pp in p): i1, (n1, d1) = max(((i, pp) for i, pp in enumerate(p) i...
sPermutations :: [a] -> [([a], Int)] sPermutations = flip zip (cycle [-1, 1]) . foldr aux [[]] where aux x items = do (f, item) <- zip (repeat id) items f (insertEv x item) insertEv x [] = [[x]] insertEv x l@(y:ys) = (x : l) : ((y :) <$> insertEv x ys) main :: IO () main = do putStrLn "3 it...
Rewrite the snippet below in Haskell so it works the same as the original Python code.
import random random.seed() attributes_total = 0 count = 0 while attributes_total < 75 or count < 2: attributes = [] for attribute in range(0, 6): rolls = [] for roll in range(0, 4): result = random.randint(1, 6) rolls.append(result) sorted_rol...
import Control.Monad (replicateM) import System.Random (randomRIO) import Data.Bool (bool) import Data.List (sort) character :: IO [Int] character = discardUntil (((&&) . (75 <) . sum) <*> ((2 <=) . length . filter (15 <=))) (replicateM 6 $ sum . tail . sort <$> replicateM 4 (randomRIO (1, 6 :: Int))) disca...
Change the following Python code into Haskell without altering its purpose.
import itertools def cycler(start_items): return itertools.cycle(start_items).__next__ def _kolakoski_gen(start_items): s, k = [], 0 c = cycler(start_items) while True: c_next = c() s.append(c_next) sk = s[k] yield sk if sk > 1: s += [c_next] * (sk - 1)...
import Data.List (group) import Control.Monad (forM_) replicateAtLeastOne :: Int -> a -> [a] replicateAtLeastOne n x = x : replicate (n-1) x zipWithLazy :: (a -> b -> c) -> [a] -> [b] -> [c] zipWithLazy f ~(x:xs) ~(y:ys) = f x y : zipWithLazy f xs ys kolakoski :: [Int] -> [Int] kolakoski items = s where s = concat...
Convert the following code from Python to Haskell, ensuring the logic remains intact.
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 sequence(max_n=None): n = 0 while True: n += 1 ii = 0 if max_n is not No...
import Data.List (find, group, sort) import Data.Maybe (mapMaybe) import Data.Numbers.Primes (primeFactors) a005179 :: [Int] a005179 = mapMaybe ( \n -> find ((n ==) . succ . length . properDivisors) [1 ..] ) [1 ..] main :: IO () main = print $ take 15 a005179 properDivi...
Change the following Python code into Haskell without altering its purpose.
bar = '▁▂▃▄▅▆▇█' barcount = len(bar) def sparkline(numbers): mn, mx = min(numbers), max(numbers) extent = mx - mn sparkline = ''.join(bar[min([barcount - 1, int((n - mn) / extent * barcount)])] for n in numbers) return mn, mx, sparkline if __...
import Data.List.Split (splitOneOf) import Data.Char (chr) toSparkLine :: [Double] -> String toSparkLine xs = map cl xs where top = maximum xs bot = minimum xs range = top - bot cl x = chr $ 0x2581 + floor (min 7 ((x - bot) / range * 8)) makeSparkLine :: String -> (String, Stats) makeSparkLine xs =...
Transform the following Python implementation into Haskell, maintaining the same output and logic.
from difflib import ndiff def levenshtein(str1, str2): result = "" pos, removed = 0, 0 for x in ndiff(str1, str2): if pos<len(str1) and str1[pos] == x[2]: pos += 1 result += x[2] if x[0] == "-": removed += 1 continue else: if r...
costs :: String -> String -> [[Int]] costs s1 s2 = reverse $ reverse <$> matrix where matrix = scanl transform [0 .. length s1] s2 transform ns@(n:ns1) c = scanl calc (n + 1) $ zip3 s1 ns ns1 where calc z (c1, x, y) = minimum [ y + 1, z + 1 , x + fromEnum (c1 ...
Generate a Haskell translation of this Python snippet without changing its computational steps.
def longest_increasing_subsequence(X): N = len(X) P = [0] * N M = [0] * (N+1) L = 0 for i in range(N): lo = 1 hi = L while lo <= hi: mid = (lo+hi)//2 if (X[M[mid]] < X[i]): lo = mid+1 else: hi = mid-1 ...
import Data.Ord ( comparing ) import Data.List ( maximumBy, subsequences ) import Data.List.Ordered ( isSorted, nub ) lis :: Ord a => [a] -> [a] lis = maximumBy (comparing length) . map nub . filter isSorted . subsequences main = do print $ lis [3,2,6,4,5,1] print $ lis [0,8,4,...
Please provide an equivalent version of this Python code in Haskell.
import math szamok=[] limit = 1000 for i in range(1,int(math.ceil(math.sqrt(limit))),2): num = i*i if (num < 1000 and num > 99): szamok.append(num) print(szamok)
main :: IO () main = print $ takeWhile (<1000) $ filter odd $ map (^2) $ [10..]
Produce a language-to-language conversion: from Python to Haskell, same semantics.
def isPrime(n): for i in range(2, int(n**0.5) + 1): if n % i == 0: return False return True def digSum(n, b): s = 0 while n: s += (n % b) n = n // b return s if __name__ == '__main__': for n in range(11, 99): if isPrime(digSum(n**3, 10)) an...
import Data.Bifunctor (first) import Data.Numbers.Primes (isPrime) p :: Int -> Bool p = ((&&) . primeDigitSum . (^ 2)) <*> (primeDigitSum . (^ 3)) main :: IO () main = print $ filter p [2 .. 99] primeDigitSum :: Int -> Bool primeDigitSum = isPrime . digitSum 10 digitSum :: Int -> Int -> Int digitSum base ...
Write a version of this Python function in Haskell with identical behavior.
>>> name = raw_input("Enter a variable name: ") Enter a variable name: X >>> globals()[name] = 42 >>> X 42
data Var a = Var String a deriving Show main = do putStrLn "please enter you variable name" vName <- getLine let var = Var vName 42 putStrLn $ "this is your variable: " ++ show var
Port the provided Python code into Haskell while preserving the original functionality.
from primesieve.numpy import primes from math import isqrt import numpy as np max_order = 9 blocks = [primes(10**n, 10**(n + 1)) for n in range(max_order)] def smallest_brilliant(lb): pos = 1 root = isqrt(lb) for blk in blocks: n = len(blk) if blk[-1]*blk[-1] < lb: pos += n*(n...
import Control.Monad (join) import Data.Bifunctor (bimap) import Data.List (intercalate, transpose) import Data.List.Split (chunksOf, splitWhen) import Data.Numbers.Primes (primeFactors) import Text.Printf (printf) isBrilliant :: (Integral a, Show a) => a -> Bool isBrilliant n = case primeFactors n of [a, b] -> le...
Translate this program into Haskell but keep the logic exactly as in Python.
from primesieve.numpy import primes from math import isqrt import numpy as np max_order = 9 blocks = [primes(10**n, 10**(n + 1)) for n in range(max_order)] def smallest_brilliant(lb): pos = 1 root = isqrt(lb) for blk in blocks: n = len(blk) if blk[-1]*blk[-1] < lb: pos += n*(n...
import Control.Monad (join) import Data.Bifunctor (bimap) import Data.List (intercalate, transpose) import Data.List.Split (chunksOf, splitWhen) import Data.Numbers.Primes (primeFactors) import Text.Printf (printf) isBrilliant :: (Integral a, Show a) => a -> Bool isBrilliant n = case primeFactors n of [a, b] -> le...
Convert this Python snippet to Haskell and keep its semantics consistent.
from fractions import Fraction from math import floor from itertools import islice, groupby def cw(): a = Fraction(1) while True: yield a a = 1 / (2 * floor(a) + 1 - a) def r2cf(rational): num, den = rational.numerator, rational.denominator while den: num, (digit, den) = den, ...
import Control.Monad (forM_) import Data.Bool (bool) import Data.List.NonEmpty (NonEmpty, fromList, toList, unfoldr) import Text.Printf (printf) calkinWilfs :: [Rational] calkinWilfs = iterate (recip . succ . ((-) =<< (2 *) . fromIntegral . floor)) 1 calkinWilfIdx :: Rational -> Integer calkinWilfIdx = rld . cfo ...
Change the following Python code into Haskell without altering its purpose.
from fractions import Fraction from math import floor from itertools import islice, groupby def cw(): a = Fraction(1) while True: yield a a = 1 / (2 * floor(a) + 1 - a) def r2cf(rational): num, den = rational.numerator, rational.denominator while den: num, (digit, den) = den, ...
import Control.Monad (forM_) import Data.Bool (bool) import Data.List.NonEmpty (NonEmpty, fromList, toList, unfoldr) import Text.Printf (printf) calkinWilfs :: [Rational] calkinWilfs = iterate (recip . succ . ((-) =<< (2 *) . fromIntegral . floor)) 1 calkinWilfIdx :: Rational -> Integer calkinWilfIdx = rld . cfo ...
Write the same code in Haskell as shown below in Python.
from __future__ import print_function def order_disjoint_list_items(data, items): itemindices = [] for item in set(items): itemcount = items.count(item) lastindex = [-1] for i in range(itemcount): lastindex.append(data.index(item, lastindex[-1] + 1)) it...
import Data.List (mapAccumL, sort) order :: Ord a => [[a]] -> [a] order [ms, ns] = snd . mapAccumL yu ls $ ks where ks = zip ms [(0 :: Int) ..] ls = zip ns . sort . snd . foldl go (sort ns, []) . sort $ ks yu ((u, v):us) (_, y) | v == y = (us, u) yu ys (x, _) = (ys, x) go (u:us, ys) (x,...
Transform the following Python implementation into Haskell, maintaining the same output and logic.
from itertools import takewhile def palindromicPrimes(): def p(n): s = str(n) return s == s[::-1] return (n for n in primes() if p(n)) def main(): print('\n'.join( str(x) for x in takewhile( lambda n: 1000 > n, palindromicPrimes() ) ...
import Data.Numbers.Primes palindromicPrimes :: [Integer] palindromicPrimes = filter (((==) <*> reverse) . show) primes main :: IO () main = mapM_ print $ takeWhile (1000 >) palindromicPrimes
Produce a language-to-language conversion: from Python to Haskell, same semantics.
from itertools import takewhile def palindromicPrimes(): def p(n): s = str(n) return s == s[::-1] return (n for n in primes() if p(n)) def main(): print('\n'.join( str(x) for x in takewhile( lambda n: 1000 > n, palindromicPrimes() ) ...
import Data.Numbers.Primes palindromicPrimes :: [Integer] palindromicPrimes = filter (((==) <*> reverse) . show) primes main :: IO () main = mapM_ print $ takeWhile (1000 >) palindromicPrimes
Please provide an equivalent version of this Python code in Haskell.
from functools import reduce from itertools import count, islice def sylvester(): def go(n): return 1 + reduce( lambda a, x: a * go(x), range(0, n), 1 ) if 0 != n else 2 return map(go, count(0)) def main(): print("First 10 terms of OEI...
sylvester :: [Integer] sylvester = map s [0 ..] where s 0 = 2 s n = succ $ foldr ((*) . s) 1 [0 .. pred n] main :: IO () main = do putStrLn "First 10 elements of Sylvester's sequence:" putStr $ unlines $ map show $ take 10 sylvester putStr "\nSum of reciprocals by sum over map: " print $ sum $ map (...
Port the following code from Python to Haskell with equivalent syntax and logic.
from fractions import Fraction def harmonic_series(): n, h = Fraction(1), Fraction(1) while True: yield h h += 1 / (n + 1) n += 1 if __name__ == '__main__': from itertools import islice for n, d in (h.as_integer_ratio() for h in islice(harmonic_series(), 20)): print(n,...
import Data.List (find) import Data.Ratio harmonic :: [Rational] harmonic = scanl1 (\a x -> a + 1 / x) [1 ..] main :: IO () main = do putStrLn "First 20 terms:" mapM_ putStrLn $ showRatio <$> take 20 harmonic putStrLn "\n100th term:" putStrLn $ showRatio (harmonic !! 99) putStrLn "" put...
Ensure the translated Haskell code behaves exactly like the original Python snippet.
python Python 2.6.1 (r261:67517, Dec 4 2008, 16:51:00) [MSC v.1500 32 bit (Intel)] on win32 Type "help", "copyright", "credits" or "license" for more information. >>> def f(string1, string2, separator): return separator.join([string1, '', string2]) >>> f('Rosetta', 'Code', ':') 'Rosetta::Code' >>>
$ ghci ___ ___ _ / _ \ /\ /\/ __(_) / /_\// /_/ / / | | GHC Interactive, version 6.4.2, for Haskell 98. / /_\\/ __ / /___| | http://www.haskell.org/ghc/ \____/\/ /_/\____/|_| Type :? for help. Loading package base-1.0 ... linking ... done. Prelude> let f as bs sep = as ++ sep ++ sep ++ ...
Rewrite this program in Haskell while keeping its functionality equivalent to the Python version.
import re male2female=u re_nl=re.compile(r",[ \n]*") m2f=[ tok.split(" ") for tok in re_nl.split(male2female) ] switch={} words=[] re_plural=re.compile("E*S$") re_ES=re.compile("ES$") def gen_pluralize(m,f): yield re_plural.sub("",m),re_plural.sub("",f) yield re_ES.sub("es",m),re_ES.sub("es",f) yie...
id
Write the same algorithm in Haskell as shown in this Python implementation.
import re male2female=u re_nl=re.compile(r",[ \n]*") m2f=[ tok.split(" ") for tok in re_nl.split(male2female) ] switch={} words=[] re_plural=re.compile("E*S$") re_ES=re.compile("ES$") def gen_pluralize(m,f): yield re_plural.sub("",m),re_plural.sub("",f) yield re_ES.sub("es",m),re_ES.sub("es",f) yie...
id
Maintain the same structure and functionality when rewriting this code in Haskell.
def rank(x): return int('a'.join(map(str, [1] + x)), 11) def unrank(n): s = '' while n: s,n = "0123456789a"[n%11] + s, n//11 return map(int, s.split('a'))[1:] l = [1, 2, 3, 10, 100, 987654321] print l n = rank(l) print n l = unrank(n) print l
import Data.List toBase :: Int -> Integer -> [Int] toBase b = unfoldr f where f 0 = Nothing f n = let (q, r) = n `divMod` fromIntegral b in Just (fromIntegral r, q) fromBase :: Int -> [Int] -> Integer fromBase n lst = foldr (\x r -> fromIntegral n*r + fromIntegral x) 0 lst listToInt :: Int...
Generate an equivalent Haskell version of this Python code.
import random print(random.sample(range(1, 21), 20))
import Data.List (sortBy) import Data.Ord (comparing) import System.Random (newStdGen, randomRs) inRandomOrder :: [a] -> IO [a] inRandomOrder xs = fmap fst . sortBy (comparing snd) . zip xs <$> (randomRs (0, 1) <$> newStdGen :: IO [Double]) main :: IO () main = inRandomOrder [1 .. 20] >>= print
Generate an equivalent Haskell version of this Python code.
from sympy import isprime def print50(a, width=8): for i, n in enumerate(a): print(f'{n: {width},}', end='\n' if (i + 1) % 10 == 0 else '') def generate_cyclops(maxdig=9): yield 0 for d in range((maxdig + 1) // 2): arr = [str(i) for i in range(10**d, 10**(d+1)) if not('0' in str(i))] ...
import Control.Monad (replicateM) import Data.Numbers.Primes (isPrime) cyclops :: [Integer] cyclops = [0 ..] >>= go where go 0 = [0] go n = (\s -> read s :: Integer) <$> (fmap ((<>) . (<> "0")) >>= (<*>)) (replicateM n ['1' .. '9']) blindPrime :: Integer -> Bool blindPrime n = le...
Port the following code from Python to Haskell with equivalent syntax and logic.
def prime(limite, mostrar): global columna columna = 0 for n in range(limite): strn = str(n) if isPrime(n) and ('123' in str(n)): columna += 1 if mostrar == True: print(n, end=" "); if columna % 8 == 0: ...
import Data.List ( isInfixOf ) isPrime :: Int -> Bool isPrime n |n < 2 = False |otherwise = null $ filter (\i -> mod n i == 0 ) [2 .. root] where root :: Int root = floor $ sqrt $ fromIntegral n condition :: Int -> Bool condition n = isPrime n && isInfixOf "123" ( show n ) solution :: [Int] ...
Port the following code from Python to Haskell with equivalent syntax and logic.
def prime(limite, mostrar): global columna columna = 0 for n in range(limite): strn = str(n) if isPrime(n) and ('123' in str(n)): columna += 1 if mostrar == True: print(n, end=" "); if columna % 8 == 0: ...
import Data.List ( isInfixOf ) isPrime :: Int -> Bool isPrime n |n < 2 = False |otherwise = null $ filter (\i -> mod n i == 0 ) [2 .. root] where root :: Int root = floor $ sqrt $ fromIntegral n condition :: Int -> Bool condition n = isPrime n && isInfixOf "123" ( show n ) solution :: [Int] ...
Maintain the same structure and functionality when rewriting this code in Haskell.
def isPrime(n): for i in range(2, int(n**0.5) + 1): if n % i == 0: return False return True if __name__ == '__main__': print("p q pq+2") print("-----------------------") for p in range(2, 499): if not isPrime(p): continue q = p...
import Data.List.Split ( divvy ) isPrime :: Int -> Bool isPrime n |n < 2 = False |otherwise = null $ filter (\i -> mod n i == 0 ) [2 .. root] where root :: Int root = floor $ sqrt $ fromIntegral n solution :: [Int] solution = map head $ filter (\li -> isPrime ((head li * last li) + 2 )) $ d...
Generate a Haskell translation of this Python snippet without changing its computational steps.
def isPrime(n): for i in range(2, int(n**0.5) + 1): if n % i == 0: return False return True if __name__ == '__main__': print("p q pq+2") print("-----------------------") for p in range(2, 499): if not isPrime(p): continue q = p...
import Data.List.Split ( divvy ) isPrime :: Int -> Bool isPrime n |n < 2 = False |otherwise = null $ filter (\i -> mod n i == 0 ) [2 .. root] where root :: Int root = floor $ sqrt $ fromIntegral n solution :: [Int] solution = map head $ filter (\li -> isPrime ((head li * last li) + 2 )) $ d...
Produce a language-to-language conversion: from Python to Haskell, same semantics.
import math print("working...") list = [(3,4,34,25,9,12,36,56,36),(2,8,81,169,34,55,76,49,7),(75,121,75,144,35,16,46,35)] Squares = [] def issquare(x): for p in range(x): if x == p*p: return 1 for n in range(3): for m in range(len(list[n])): if issquare(list[n][m]): Squares.append(list[n][m]) Squares.sor...
import Data.List (sort) squaresSorted :: Integral a => [[a]] -> [a] squaresSorted = sort . (filter isPerfectSquare =<<) isPerfectSquare :: Integral a => a -> Bool isPerfectSquare n = let sqr = (floor . sqrt) (fromIntegral n :: Double) in n == sqr ^ 2 main :: IO () main = print $ squaresSorted [ [3, 4...
Port the following code from Python to Haskell with equivalent syntax and logic.
import math print("working...") list = [(3,4,34,25,9,12,36,56,36),(2,8,81,169,34,55,76,49,7),(75,121,75,144,35,16,46,35)] Squares = [] def issquare(x): for p in range(x): if x == p*p: return 1 for n in range(3): for m in range(len(list[n])): if issquare(list[n][m]): Squares.append(list[n][m]) Squares.sor...
import Data.List (sort) squaresSorted :: Integral a => [[a]] -> [a] squaresSorted = sort . (filter isPerfectSquare =<<) isPerfectSquare :: Integral a => a -> Bool isPerfectSquare n = let sqr = (floor . sqrt) (fromIntegral n :: Double) in n == sqr ^ 2 main :: IO () main = print $ squaresSorted [ [3, 4...
Preserve the algorithm and functionality while converting the code from Python to Haskell.
var x = 0 var y = 0 There are also multi-line comments Everything inside of ] discard
i code = True let u x = x x (this code not compiled) Are you? -} i code = True i code = True
Produce a language-to-language conversion: from Python to Haskell, same semantics.
print("working...") print("First 20 Cullen numbers:") for n in range(1,21): num = n*pow(2,n)+1 print(str(num),end= " ") print() print("First 20 Woodall numbers:") for n in range(1,21): num = n*pow(2,n)-1 print(str(num),end=" ") print() print("done...")
findCullen :: Int -> Integer findCullen n = toInteger ( n * 2 ^ n + 1 ) cullens :: [Integer] cullens = map findCullen [1 .. 20] woodalls :: [Integer] woodalls = map (\i -> i - 2 ) cullens main :: IO ( ) main = do putStrLn "First 20 Cullen numbers:" print cullens putStrLn "First 20 Woodall numbers:" print...
Port the provided Python code into Haskell while preserving the original functionality.
revision = "October 13th 2020" elements = ( "hydrogen helium lithium beryllium boron carbon nitrogen oxygen fluorine " "neon sodium magnesium aluminum silicon phosphorous sulfur chlorine argon " "potassium calcium scandium titanium vanadium chromium manganese iron " "cobalt nickel copper zinc gall...
elements = words "hydrogen \ \ fluorine neon sodium magnesium \ \ aluminum silicon phosphorous sulfur \ \ chlorine argon potassium calcium \ \ scandium titanium vanadium chromium \ \ manganese iron cobalt nickel...
Rewrite this program in Haskell while keeping its functionality equivalent to the Python version.
def makechange(denominations = [1,2,5,10,20,50,100,200], total = 988): print(f"Available denominations: {denominations}. Total is to be: {total}.") coins, remaining = sorted(denominations, reverse=True), total for n in range(len(coins)): coinsused, remaining = divmod(remaining, coins[n]) if ...
import Data.List (mapAccumL) import Data.Tuple (swap) change :: [Int] -> Int -> [(Int, Int)] change xs n = zip (snd $ mapAccumL go n xs) xs where go m v = swap (quotRem m v) main :: IO () main = mapM_ print $ change [200, 100, 50, 20, 10, 5, 2, 1] 988
Can you help me rewrite this code in Haskell instead of Python, keeping it the same logically?
def longestPalindromes(s): k = s.lower() palindromes = [ palExpansion(k)(ab) for ab in palindromicNuclei(k) ] maxLength = max([ len(x) for x in palindromes ]) if palindromes else 1 return ( [ x for x in palindromes if maxLength == len(x) ...
longestPalindromes :: String -> ([String], Int) longestPalindromes [] = ([], 0) longestPalindromes s = go $ palindromes s where go xs | null xs = (return <$> s, 1) | otherwise = (filter ((w ==) . length) xs, w) where w = maximum $ length <$> xs palindromes :: String -> [String] palind...
Translate this program into Haskell but keep the logic exactly as in Python.
def get_next_character(f): c = f.read(1) while c: while True: try: yield c.decode('utf-8') except UnicodeDecodeError: c += f.read(1) else: c = f.read(1) break with open("input.txt","rb") as f: for c in get_next_character(f): ...
#!/usr/bin/env runhaskell import System.Environment (getArgs) import System.IO ( Handle, IOMode (..), hGetChar, hIsEOF, hSetEncoding, stdin, utf8, withFile ) import Control.Monad (forM_, unless) import Text.Printf (printf) import Data.Char (ord) processCharacters :: Handle -> IO () processCharac...
Can you help me rewrite this code in Haskell instead of Python, keeping it the same logically?
import sys, os import random import time def print_there(x, y, text): sys.stdout.write("\x1b7\x1b[%d;%df%s\x1b8" % (x, y, text)) sys.stdout.flush() class Ball(): def __init__(self): self.x = 0 self.y = 0 def update(self): self.x += random.randint(0,1) self...
import Data.Map hiding (map, filter) import Graphics.Gloss import Control.Monad.Random data Ball = Ball { position :: (Int, Int), turns :: [Int] } type World = ( Int , [Ball] , Map Int Int ) updateWorld :: World -> World updateWorld (nRows, balls, bins) | y < -nRows-5 ...
Port the following code from Python to Haskell with equivalent syntax and logic.
from __future__ import print_function from itertools import takewhile maxsum = 99 def get_primes(max): if max < 2: return [] lprimes = [2] for x in range(3, max + 1, 2): for p in lprimes: if x % p == 0: break else: lprimes.append(x) retur...
import Data.Numbers.Primes (isPrime) import Data.List type Memo2 a = Memo (Memo a) data Memo a = Node a (Memo a) (Memo a) deriving Functor memo :: Integral a => Memo p -> a -> p memo (Node a l r) n | n == 0 = a | odd n = memo l (n `div` 2) | otherwise = memo r (n `div` 2 - 1) nats :: Integral a => Memo ...
Write the same algorithm in Haskell as shown in this Python implementation.
from itertools import count def firstSquareWithPrefix(n): pfx = str(n) lng = len(pfx) return int( next( s for s in ( str(x * x) for x in count(0) ) if pfx == s[0:lng] ) ) def main(): print('\n'.join([ str(...
import Control.Monad (join) import Data.List (find, intercalate, isPrefixOf, transpose) import Data.List.Split (chunksOf) import Text.Printf (printf) firstSquareWithPrefix :: Int -> Int firstSquareWithPrefix n = unDigits match where ds = digits n Just match = find (isPrefixOf ds) squareDigits squareDigits...
Translate the given Python code snippet into Haskell without altering its behavior.
from itertools import count def firstSquareWithPrefix(n): pfx = str(n) lng = len(pfx) return int( next( s for s in ( str(x * x) for x in count(0) ) if pfx == s[0:lng] ) ) def main(): print('\n'.join([ str(...
import Control.Monad (join) import Data.List (find, intercalate, isPrefixOf, transpose) import Data.List.Split (chunksOf) import Text.Printf (printf) firstSquareWithPrefix :: Int -> Int firstSquareWithPrefix n = unDigits match where ds = digits n Just match = find (isPrefixOf ds) squareDigits squareDigits...
Convert the following code from Python to Haskell, ensuring the logic remains intact.
def circle_sort_backend(A:list, L:int, R:int)->'sort A in place, returning the number of swaps': n = R-L if n < 2: return 0 swaps = 0 m = n//2 for i in range(m): if A[R-(i+1)] < A[L+i]: (A[R-(i+1)], A[L+i],) = (A[L+i], A[R-(i+1)],) swaps += 1 if ...
import Data.Bool (bool) circleSort :: Ord a => [a] -> [a] circleSort xs = if swapped then circleSort ks else ks where (swapped,ks) = go False xs (False,[]) go d [] sks = sks go d [x] (s,ks) = (s,x:ks) go d xs (s,ks) = let (st,_,ls,rs) = halve d s xs xs in go False ls (go True rs (s...
Produce a functionally identical Haskell code for the snippet given in Python.
import urllib.request from collections import Counter GRID = def getwords(url='http://wiki.puzzlers.org/pub/wordlists/unixdict.txt'): "Return lowercased words of 3 to 9 characters" words = urllib.request.urlopen(url).read().decode().strip().lower().split() return (w for w in words if 2 < len(w) < 10) ...
import Data.Char (toLower) import Data.List (sort) import System.IO (readFile) gridWords :: [String] -> [String] -> [String] gridWords grid = filter ( ((&&) . (2 <) . length) <*> (((&&) . elem mid) <*> wheelFit wheel) ) where cs = toLower <$> concat grid wheel = sort cs mid = cs !! 4 ...
Translate this program into Haskell but keep the logic exactly as in Python.
def getitem(s, depth=0): out = [""] while s: c = s[0] if depth and (c == ',' or c == '}'): return out,s if c == '{': x = getgroup(s[1:], depth+1) if x: out,s = [a+b for a in out for b in x[0]], x[1] continue if c...
import qualified Text.Parsec as P showExpansion :: String -> String showExpansion = (<>) . (<> "\n parser :: P.Parsec String u [String] parser = expansion P.anyChar expansion :: P.Parsec String u Char -> P.Parsec String u [String] expansion = fmap expand . P.many . ((P.try alts P.<|> P.try alt1 P.<|> escape)...
Preserve the algorithm and functionality while converting the code from Python to Haskell.
from itertools import islice class INW(): def __init__(self, **wheels): self._wheels = wheels self.isect = {name: self._wstate(name, wheel) for name, wheel in wheels.items()} def _wstate(self, name, wheel): "Wheel state holder" assert all(val in...
import Data.Char (isDigit) import Data.List (mapAccumL) import qualified Data.Map.Strict as M import Data.Maybe (fromMaybe) clockWorkTick :: M.Map Char String -> (M.Map Char String, Char) clockWorkTick = flip click 'A' where click wheels name | isDigit name = (wheels, name) | otherwise = ...
Change the programming language of this snippet from Python to Haskell without modifying what it does.
from itertools import islice class INW(): def __init__(self, **wheels): self._wheels = wheels self.isect = {name: self._wstate(name, wheel) for name, wheel in wheels.items()} def _wstate(self, name, wheel): "Wheel state holder" assert all(val in...
import Data.Char (isDigit) import Data.List (mapAccumL) import qualified Data.Map.Strict as M import Data.Maybe (fromMaybe) clockWorkTick :: M.Map Char String -> (M.Map Char String, Char) clockWorkTick = flip click 'A' where click wheels name | isDigit name = (wheels, name) | otherwise = ...