Instruction stringlengths 45 106 | input_code stringlengths 1 13.7k | output_code stringlengths 1 13.7k |
|---|---|---|
Please provide an equivalent version of this Python code in Haskell. | import urllib
import re
def fix(x):
p = re.compile(r'<[^<]*?>')
return p.sub('', x).replace('&', '&')
class YahooSearch:
def __init__(self, query, page=1):
self.query = query
self.page = page
self.url = "http://search.yahoo.com/search?p=%s&b=%s" %(self.query, ((self.pag... | import Network.HTTP
import Text.Parsec
data YahooSearchItem = YahooSearchItem {
itemUrl, itemTitle, itemContent :: String }
data YahooSearch = YahooSearch {
searchQuery :: String,
searchPage :: Int,
searchItems :: [YahooSearchItem] }
yahooUrl = "http://search.yahoo.com/search?p="
yahoo :: Stri... |
Produce a language-to-language conversion: from Python to Haskell, same semantics. | from collections import namedtuple
from math import sqrt
Pt = namedtuple('Pt', 'x, y')
Circle = Cir = namedtuple('Circle', 'x, y, r')
def circles_from_p1p2r(p1, p2, r):
'Following explanation at http://mathforum.org/library/drmath/view/53027.html'
if r == 0.0:
raise ValueError('radius of zero')
(x... | add (a, b) (x, y) = (a + x, b + y)
sub (a, b) (x, y) = (a - x, b - y)
magSqr (a, b) = (a ^^ 2) + (b ^^ 2)
mag a = sqrt $ magSqr a
mul (a, b) c = (a * c, b * c)
div2 (a, b) c = (a / c, b / c)
perp (a, b) = (negate b, a)
norm a = a `div2` mag a
circlePoints :: (Ord a, Floating a... |
Convert this Python block to Haskell, preserving its control flow and logic. | from collections import namedtuple
from math import sqrt
Pt = namedtuple('Pt', 'x, y')
Circle = Cir = namedtuple('Circle', 'x, y, r')
def circles_from_p1p2r(p1, p2, r):
'Following explanation at http://mathforum.org/library/drmath/view/53027.html'
if r == 0.0:
raise ValueError('radius of zero')
(x... | add (a, b) (x, y) = (a + x, b + y)
sub (a, b) (x, y) = (a - x, b - y)
magSqr (a, b) = (a ^^ 2) + (b ^^ 2)
mag a = sqrt $ magSqr a
mul (a, b) c = (a * c, b * c)
div2 (a, b) c = (a / c, b / c)
perp (a, b) = (negate b, a)
norm a = a `div2` mag a
circlePoints :: (Ord a, Floating a... |
Keep all operations the same but rewrite the snippet in Haskell. | from __future__ import division
import math
from operator import mul
from itertools import product
from functools import reduce
def fac(n):
step = lambda x: 1 + x*4 - (x//2)*2
maxq = int(math.floor(math.sqrt(n)))
d = 1
q = n % 2 == 0 and 2 or 3
while q <= maxq and n % q != 0:
q = st... | import Data.List (sort)
import Control.Arrow ((&&&))
vampires :: [Int]
vampires = filter (not . null . fangs) [1 ..]
fangs :: Int -> [(Int, Int)]
fangs n
| odd w = []
| otherwise = ((,) <*> quot n) <$> filter isfang (integerFactors n)
where
ndigit :: Int -> Int
ndigit 0 = 0
ndigit n = 1 + ndigit (q... |
Can you help me rewrite this code in Haskell instead of Python, keeping it the same logically? | import random
n = 52
Black, Red = 'Black', 'Red'
blacks = [Black] * (n // 2)
reds = [Red] * (n // 2)
pack = blacks + reds
random.shuffle(pack)
black_stack, red_stack, discard = [], [], []
while pack:
top = pack.pop()
if top == Black:
black_stack.append(pack.pop())
else:
red_stack.appen... | import System.Random (randomRIO)
import Data.List (partition)
import Data.Monoid ((<>))
main :: IO [Int]
main = do
ns <- knuthShuffle [1 .. 52]
let (rs_, bs_, discards) = threeStacks (rb <$> ns)
nSwap <- randomRIO (1, min (length rs_) (length bs_))
let (rs, bs) = exchange nSwap rs_ bs_
let rr... |
Convert the following code from Python to Haskell, ensuring the logic remains intact. | import random
n = 52
Black, Red = 'Black', 'Red'
blacks = [Black] * (n // 2)
reds = [Red] * (n // 2)
pack = blacks + reds
random.shuffle(pack)
black_stack, red_stack, discard = [], [], []
while pack:
top = pack.pop()
if top == Black:
black_stack.append(pack.pop())
else:
red_stack.appen... | import System.Random (randomRIO)
import Data.List (partition)
import Data.Monoid ((<>))
main :: IO [Int]
main = do
ns <- knuthShuffle [1 .. 52]
let (rs_, bs_, discards) = threeStacks (rb <$> ns)
nSwap <- randomRIO (1, min (length rs_) (length bs_))
let (rs, bs) = exchange nSwap rs_ bs_
let rr... |
Port the following code from Python to Haskell with equivalent syntax and logic. | :- initialization(main).
faces([a,k,q,j,10,9,8,7,6,5,4,3,2]).
face(F) :- faces(Fs), member(F,Fs).
suit(S) :- member(S, ['♥','♦','♣','♠']).
best_hand(Cards,H) :-
straight_flush(Cards,C) -> H = straight-flush(C)
; many_kind(Cards,F,4) -> H = four-of-a-kind(F)
; full_house(Cards,F1,F2) -> H = full-house(F1... |
import Data.Function (on)
import Data.List (group, nub, any, sort, sortBy)
import Data.Maybe (mapMaybe)
import Text.Read (readMaybe)
data Suit = Club | Diamond | Spade | Heart deriving (Show, Eq)
data Rank = Ace | Two | Three | Four | Five | Six | Seven
| Eight | Nine | Ten | Jack | Queen | Kin... |
Can you help me rewrite this code in Haskell instead of Python, keeping it the same logically? | :- initialization(main).
faces([a,k,q,j,10,9,8,7,6,5,4,3,2]).
face(F) :- faces(Fs), member(F,Fs).
suit(S) :- member(S, ['♥','♦','♣','♠']).
best_hand(Cards,H) :-
straight_flush(Cards,C) -> H = straight-flush(C)
; many_kind(Cards,F,4) -> H = four-of-a-kind(F)
; full_house(Cards,F1,F2) -> H = full-house(F1... |
import Data.Function (on)
import Data.List (group, nub, any, sort, sortBy)
import Data.Maybe (mapMaybe)
import Text.Read (readMaybe)
data Suit = Club | Diamond | Spade | Heart deriving (Show, Eq)
data Rank = Ace | Two | Three | Four | Five | Six | Seven
| Eight | Nine | Ten | Jack | Queen | Kin... |
Convert the following code from Python to Haskell, ensuring the logic remains intact. | from functools import wraps
from turtle import *
def memoize(obj):
cache = obj.cache = {}
@wraps(obj)
def memoizer(*args, **kwargs):
key = str(args) + str(kwargs)
if key not in cache:
cache[key] = obj(*args, **kwargs)
return cache[key]
return memoizer
@memoize
def f... | import Data.List (unfoldr)
import Data.Bool (bool)
import Data.Semigroup (Sum(..), Min(..), Max(..))
import System.IO (writeFile)
fibonacciWord :: a -> a -> [[a]]
fibonacciWord a b = unfoldr (\(a,b) -> Just (a, (b, a <> b))) ([a], [b])
toPath :: [Bool] -> ((Min Int, Max Int, Min Int, Max Int), String)
toPath = foldMa... |
Maintain the same structure and functionality when rewriting this code in Haskell. | from __future__ import print_function
import random
from time import sleep
first = random.choice([True, False])
you = ''
if first:
me = ''.join(random.sample('HT'*3, 3))
print('I choose first and will win on first seeing {} in the list of tosses'.format(me))
while len(you) != 3 or any(ch not in 'HT' for c... | import qualified Data.List as L
import System.IO
import System.Random
data CoinToss = H | T deriving (Read, Show, Eq)
parseToss :: String -> [CoinToss]
parseToss [] = []
parseToss (s:sx)
| s == 'h' || s == 'H' = H : parseToss sx
| s == 't' || s == 'T' = T : parseToss sx
| otherwise = parseToss sx
notToss :: Co... |
Convert this Python block to Haskell, preserving its control flow and logic. |
import turtle as t
def sier(n,length):
if n == 0:
return
for i in range(3):
sier(n - 1, length / 2)
t.fd(length)
t.rt(120)
| import Diagrams.Prelude
import Diagrams.Backend.Cairo.CmdLine
triangle = eqTriangle # fc black # lw 0
reduce t = t
===
(t ||| t)
sierpinski = iterate reduce triangle
main = defaultMain $ sierpinski !! 7
|
Port the provided Python code into Haskell while preserving the original functionality. |
import turtle as t
def sier(n,length):
if n == 0:
return
for i in range(3):
sier(n - 1, length / 2)
t.fd(length)
t.rt(120)
| import Diagrams.Prelude
import Diagrams.Backend.Cairo.CmdLine
triangle = eqTriangle # fc black # lw 0
reduce t = t
===
(t ||| t)
sierpinski = iterate reduce triangle
main = defaultMain $ sierpinski !! 7
|
Transform the following Python implementation into Haskell, maintaining the same output and logic. |
import inflect
import time
before = time.perf_counter()
p = inflect.engine()
print(' ')
print('eban numbers up to and including 1000:')
print(' ')
count = 0
for i in range(1,1001):
if not 'e' in p.number_to_words(i):
print(str(i)+' ',end='')
count += 1
print(' ')
print(' ')
print... |
import Data.List (intercalate)
import Text.Printf (printf)
import Data.List.Split (chunksOf)
isEban :: Int -> Bool
isEban n = all (`elem` [0, 2, 4, 6]) z
where
(b, r1) = n `quotRem` (10 ^ 9)
(m, r2) = r1 `quotRem` (10 ^ 6)
(t, r3) = r2 `quotRem` (10 ^ 3)
z = b : map (\x -> if x >= 30 && x <= 66 then x... |
Please provide an equivalent version of this Python code in Haskell. |
import inflect
import time
before = time.perf_counter()
p = inflect.engine()
print(' ')
print('eban numbers up to and including 1000:')
print(' ')
count = 0
for i in range(1,1001):
if not 'e' in p.number_to_words(i):
print(str(i)+' ',end='')
count += 1
print(' ')
print(' ')
print... |
import Data.List (intercalate)
import Text.Printf (printf)
import Data.List.Split (chunksOf)
isEban :: Int -> Bool
isEban n = all (`elem` [0, 2, 4, 6]) z
where
(b, r1) = n `quotRem` (10 ^ 9)
(m, r2) = r1 `quotRem` (10 ^ 6)
(t, r3) = r2 `quotRem` (10 ^ 3)
z = b : map (\x -> if x >= 30 && x <= 66 then x... |
Translate the given Python code snippet into Haskell without altering its behavior. |
from functools import (reduce)
def mayanNumerals(n):
return showIntAtBase(20)(
mayanDigit
)(n)([])
def mayanDigit(n):
if 0 < n:
r = n % 5
return [
(['●' * r] if 0 < r else []) +
(['━━'] * (n // 5))
]
else:
return ['Θ']
... | import Data.Bool (bool)
import Data.List (intercalate, transpose)
import qualified Data.Map.Strict as M
import Data.Maybe (maybe)
main :: IO ()
main =
(putStrLn . unlines) $
mayanFramed
<$> [ 4005,
8017,
326205,
886205,
1081439556,
1000000,
... |
Change the following Python code into Haskell without altering its purpose. | def monkey_coconuts(sailors=5):
"Parameterised the number of sailors using an inner loop including the last mornings case"
nuts = sailors
while True:
n0, wakes = nuts, []
for sailor in range(sailors + 1):
portion, remainder = divmod(n0, sailors)
wakes.append((n0, ... | import Control.Monad ((>=>))
import Data.Maybe (mapMaybe)
import System.Environment (getArgs)
tryFor :: Int -> Int -> Maybe Int
tryFor s = foldr (>=>) pure $ replicate s step
where
step n
| n `mod` (s - 1) == 0 = Just $ n * s `div` (s - 1) + 1
| otherwise = Nothing
main :: IO ()
main = do
arg... |
Port the following code from Python to Haskell with equivalent syntax and logic. | def monkey_coconuts(sailors=5):
"Parameterised the number of sailors using an inner loop including the last mornings case"
nuts = sailors
while True:
n0, wakes = nuts, []
for sailor in range(sailors + 1):
portion, remainder = divmod(n0, sailors)
wakes.append((n0, ... | import Control.Monad ((>=>))
import Data.Maybe (mapMaybe)
import System.Environment (getArgs)
tryFor :: Int -> Int -> Maybe Int
tryFor s = foldr (>=>) pure $ replicate s step
where
step n
| n `mod` (s - 1) == 0 = Just $ n * s `div` (s - 1) + 1
| otherwise = Nothing
main :: IO ()
main = do
arg... |
Change the programming language of this snippet from Python to Haskell without modifying what it does. | import time, calendar, sched, winsound
duration = 750
freq = 1280
bellchar = "\u2407"
watches = 'Middle,Morning,Forenoon,Afternoon,First/Last dog,First'.split(',')
def gap(n=1):
time.sleep(n * duration / 1000)
off = gap
def on(n=1):
winsound.Beep(freq, n * duration)
def bong():
on(); of... | import Control.Concurrent
import Control.Monad
import Data.Time
import Text.Printf
type Microsecond = Int
type Scheduler = TimeOfDay -> Microsecond
getTime :: TimeZone -> IO TimeOfDay
getTime tz = do
t <- getCurrentTime
return $ localTimeOfDay $ utcToLocalTime tz t
getGMTTime = getTime utc
getLocalTime... |
Translate the given Python code snippet into Haskell without altering its behavior. | import time, calendar, sched, winsound
duration = 750
freq = 1280
bellchar = "\u2407"
watches = 'Middle,Morning,Forenoon,Afternoon,First/Last dog,First'.split(',')
def gap(n=1):
time.sleep(n * duration / 1000)
off = gap
def on(n=1):
winsound.Beep(freq, n * duration)
def bong():
on(); of... | import Control.Concurrent
import Control.Monad
import Data.Time
import Text.Printf
type Microsecond = Int
type Scheduler = TimeOfDay -> Microsecond
getTime :: TimeZone -> IO TimeOfDay
getTime tz = do
t <- getCurrentTime
return $ localTimeOfDay $ utcToLocalTime tz t
getGMTTime = getTime utc
getLocalTime... |
Maintain the same structure and functionality when rewriting this code in Haskell. | import math
import pygame
from pygame.locals import *
pygame.init()
screen = pygame.display.set_mode((1024, 600))
pygame.display.set_caption("Polyspiral")
incr = 0
running = True
while running:
pygame.time.Clock().tick(60)
for event in pygame.event.get():
if event.type==QUIT:
running = False
break
inc... |
import Reflex
import Reflex.Dom
import Reflex.Dom.Time
import Data.Text (Text, pack)
import Data.Map (Map, fromList)
import Data.Time.Clock (getCurrentTime)
import Control.Monad.Trans (liftIO)
type Point = (Float,Float)
type Segment = (Point,Point)
main = mainWidget $ do
dTick <- tickLossy 0.05 =<< liftIO ge... |
Please provide an equivalent version of this Python code in Haskell. | import math
import pygame
from pygame.locals import *
pygame.init()
screen = pygame.display.set_mode((1024, 600))
pygame.display.set_caption("Polyspiral")
incr = 0
running = True
while running:
pygame.time.Clock().tick(60)
for event in pygame.event.get():
if event.type==QUIT:
running = False
break
inc... |
import Reflex
import Reflex.Dom
import Reflex.Dom.Time
import Data.Text (Text, pack)
import Data.Map (Map, fromList)
import Data.Time.Clock (getCurrentTime)
import Control.Monad.Trans (liftIO)
type Point = (Float,Float)
type Segment = (Point,Point)
main = mainWidget $ do
dTick <- tickLossy 0.05 =<< liftIO ge... |
Write a version of this Python function in Haskell with identical behavior. |
import pandas as pd
df_patients = pd.read_csv (r'patients.csv', sep = ",", decimal=".")
df_visits = pd.read_csv (r'visits.csv', sep = ",", decimal=".")
df_visits['VISIT_DATE'] = pd.to_datetime(df_visits['VISIT_DATE'])
df_merge = df_patients.merge(df_visits, on='PATIENT_ID', how='left')
df_group = df_merge.... | import Data.List
import Data.Maybe
import System.IO (readFile)
import Text.Read (readMaybe)
import Control.Applicative ((<|>))
newtype DB = DB { entries :: [Patient] }
deriving Show
instance Semigroup DB where
DB a <> DB b = normalize $ a <> b
instance Monoid DB where
mempty = DB []
normalize :: [Patient] -... |
Write the same algorithm in Haskell as shown in this Python implementation. | def setup():
size(500, 500)
generate_voronoi_diagram(width, height, 25)
saveFrame("VoronoiDiagram.png")
def generate_voronoi_diagram(w, h, num_cells):
nx, ny, nr, ng, nb = [], [], [], [], []
for i in range(num_cells):
nx.append(int(random(w)))
ny.append(int(random(h)))
nr.a... |
module Main where
import System.Random
import Data.Word
import Data.Array.Repa as Repa
import Data.Array.Repa.IO.BMP
sqDistance :: Word32 -> Word32 -> Word32 -> Word32 -> Word32
sqDistance !x1 !y1 !x2 !y2 = ((x1-x2)^2) + ((y1-y2)^2)
centers :: Int -> Int -> Array U DIM2 Word32
centers nCenters nCells =
f... |
Transform the following Python implementation into Haskell, maintaining the same output and logic. | def setup():
size(500, 500)
generate_voronoi_diagram(width, height, 25)
saveFrame("VoronoiDiagram.png")
def generate_voronoi_diagram(w, h, num_cells):
nx, ny, nr, ng, nb = [], [], [], [], []
for i in range(num_cells):
nx.append(int(random(w)))
ny.append(int(random(h)))
nr.a... |
module Main where
import System.Random
import Data.Word
import Data.Array.Repa as Repa
import Data.Array.Repa.IO.BMP
sqDistance :: Word32 -> Word32 -> Word32 -> Word32 -> Word32
sqDistance !x1 !y1 !x2 !y2 = ((x1-x2)^2) + ((y1-y2)^2)
centers :: Int -> Int -> Array U DIM2 Word32
centers nCenters nCells =
f... |
Port the provided Python code into Haskell while preserving the original functionality. | import ldap
l = ldap.initialize("ldap://ldap.example.com")
try:
l.protocol_version = ldap.VERSION3
l.set_option(ldap.OPT_REFERRALS, 0)
bind = l.simple_bind_s("me@example.com", "password")
finally:
l.unbind()
|
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... |
Preserve the algorithm and functionality while converting the code from Python to Haskell. |
import strformat
import tables
type Item = tuple[name: string; weight, value, pieces: int]
const Items: seq[Item] = @[("map", 9, 150, 1),
("compass", 13, 35, 1),
("water", 153, 200, 2),
("sandwich", 50, 60, 2),
... | inv = [("map",9,150,1), ("compass",13,35,1), ("water",153,200,2), ("sandwich",50,60,2),
("glucose",15,60,2), ("tin",68,45,3), ("banana",27,60,3), ("apple",39,40,3),
("cheese",23,30,1), ("beer",52,10,3), ("cream",11,70,1), ("camera",32,30,1),
("tshirt",24,15,2), ("trousers",48,10,2), ("umbrella",73,40,1), ("wtrous... |
Generate an equivalent Haskell version of this Python code. | board = []
given = []
start = None
def setup(s):
global board, given, start
lines = s.splitlines()
ncols = len(lines[0].split())
nrows = len(lines)
board = [[-1] * (ncols + 2) for _ in xrange(nrows + 2)]
for r, row in enumerate(lines):
for c, cell in enumerate(row.split()):
... |
import qualified Data.IntMap as I
import Data.IntMap (IntMap)
import Data.List
import Data.Maybe
import Data.Time.Clock
data BoardProblem = Board
{ cells :: IntMap (IntMap Int)
, endVal :: Int
, onePos :: (Int, Int)
, givens :: [Int]
} deriving (Show, Eq)
tupIns x y v m = I.insert x (I.insert y v (I.find... |
Port the following code from Python to Haskell with equivalent syntax and logic. | board = []
given = []
start = None
def setup(s):
global board, given, start
lines = s.splitlines()
ncols = len(lines[0].split())
nrows = len(lines)
board = [[-1] * (ncols + 2) for _ in xrange(nrows + 2)]
for r, row in enumerate(lines):
for c, cell in enumerate(row.split()):
... |
import qualified Data.IntMap as I
import Data.IntMap (IntMap)
import Data.List
import Data.Maybe
import Data.Time.Clock
data BoardProblem = Board
{ cells :: IntMap (IntMap Int)
, endVal :: Int
, onePos :: (Int, Int)
, givens :: [Int]
} deriving (Show, Eq)
tupIns x y v m = I.insert x (I.insert y v (I.find... |
Convert this Python block to Haskell, preserving its control flow and logic. | def merge_list(a, b):
out = []
while len(a) and len(b):
if a[0] < b[0]:
out.append(a.pop(0))
else:
out.append(b.pop(0))
out += a
out += b
return out
def strand(a):
i, s = 0, [a.pop(0)]
while i < len(a):
if a[i] > s[-1]:
s.append(a.pop(i))
else:
i += 1
return s
def strand_sort(a):
out = st... |
merge :: (Ord a) => [a] -> [a] -> [a]
merge [] ys = ys
merge xs [] = xs
merge (x : xs) (y : ys)
| x <= y = x : merge xs (y : ys)
| otherwise = y : merge (x : xs) ys
strandSort :: (Ord a) => [a] -> [a]
strandSort [] = []
strandSort (x : xs) = merge strand (strandSort rest) where
(strand, rest) = extractStrand x xs
... |
Generate an equivalent Haskell version of this Python code. | PI = 3.141592653589793
TWO_PI = 6.283185307179586
def normalize2deg(a):
while a < 0: a += 360
while a >= 360: a -= 360
return a
def normalize2grad(a):
while a < 0: a += 400
while a >= 400: a -= 400
return a
def normalize2mil(a):
while a < 0: a += 6400
while a >= 6400: a -= 6400
return a
def normalize... |
import Text.Printf
class (Num a, Fractional a, RealFrac a) => Angle a where
fullTurn :: a
mkAngle :: Double -> a
value :: a -> Double
fromTurn :: Double -> a
toTurn :: a -> Double
normalize :: a -> a
fromTurn t = angle t * fullTurn
toTurn a = value $ a / fullTurn
normalize a = a `modu... |
Write the same algorithm in Haskell as shown in this Python implementation. |
from xml.dom import minidom
xmlfile = file("test3.xml")
xmldoc = minidom.parse(xmlfile).documentElement
xmldoc = minidom.parseString("<inventory title="OmniCorp Store
i = xmldoc.getElementsByTagName("item")
firstItemElement = i[0]
for j in xmldoc.getElementsByTagName("price"):
print j.childNodes[0].data ... | import Data.List
import Control.Arrow
import Control.Monad
takeWhileIncl :: (a -> Bool) -> [a] -> [a]
takeWhileIncl _ [] = []
takeWhileIncl p (x:xs)
| p x = x : takeWhileIncl p xs
| otherwise = [x]
getmultiLineItem n = takeWhileIncl(not.isInfixOf ("</" ++ n)). dropWhil... |
Maintain the same structure and functionality when rewriting this code in Haskell. |
from mechanize import Browser
USER_AGENT = "Mozilla/5.0 (X11; U; Linux i686; tr-TR; rv:1.8.1.9) Gecko/20071102 Pardus/2007 Firefox/2.0.0.9"
br = Browser()
br.addheaders = [("User-agent", USER_AGENT)]
br.open("https://www.facebook.com")
br.select_form("loginform")
br['email'] = "xxxxxxx@xxxxx.com"
br['pass']... |
module Main (main) where
import Data.Aeson (Value)
import Data.Default.Class (def)
import Network.HTTP.Req
( (/:)
, GET(..)
, NoReqBody(..)
, basicAuth
, https
, jsonR... |
Can you help me rewrite this code in Haskell instead of Python, keeping it the same logically? | def mc_rank(iterable, start=1):
lastresult, fifo = None, []
for n, item in enumerate(iterable, start-1):
if item[0] == lastresult:
fifo += [item]
else:
while fifo:
yield n, fifo.pop(0)
lastresult, fifo = item[0], fifo + [item]
while fi... | import Data.List (groupBy, sortBy, intercalate)
type Item = (Int, String)
type ItemList = [Item]
type ItemGroups = [ItemList]
type RankItem a = (a, Int, String)
type RankItemList a = [RankItem a]
prepare :: ItemList -> ItemGroups
prepare = groupBy gf . sortBy (flip compare)
where
gf (a, _) (b, _) = a == b
... |
Produce a functionally identical Haskell code for the snippet given in Python. |
import re
import string
DISABLED_PREFIX = ';'
class Option(object):
def __init__(self, name, value=None, disabled=False,
disabled_prefix=DISABLED_PREFIX):
self.name = str(name)
self.value = value
self.disabled = bool(disabled)
self.... | import Data.Char (toUpper)
import qualified System.IO.Strict as S
|
Maintain the same structure and functionality when rewriting this code in Haskell. | T = [["79", "0", "1", "2", "3", "4", "5", "6", "7", "8", "9"],
["", "H", "O", "L", "", "M", "E", "S", "", "R", "T"],
["3", "A", "B", "C", "D", "F", "G", "I", "J", "K", "N"],
["7", "P", "Q", "U", "V", "W", "X", "Y", "Z", ".", "/"]]
def straddle(s):
return "".join(L[0]+T[0][L.index(c)] for c in ... | import Data.Char
import Data.Map
charToInt :: Char -> Int
charToInt c = ord c - ord '0'
decodeChar :: String -> (Char,String)
decodeChar ('7':'9':r:rs) = (r,rs)
decodeChar ('7':r:rs) = ("PQUVWXYZ. " !! charToInt r, rs)
decodeChar ('3':r:rs) = ("ABCDFGIJKN" !! charToInt r, rs)
decodeChar (r:rs) = ("H... |
Translate this program into Haskell but keep the logic exactly as in Python. | import urllib.request
import re
PLAUSIBILITY_RATIO = 2
def plausibility_check(comment, x, y):
print('\n Checking plausibility of: %s' % comment)
if x > PLAUSIBILITY_RATIO * y:
print(' PLAUSIBLE. As we have counts of %i vs %i, a ratio of %4.1f times'
% (x, y, x / y))
else:
... | import Network.HTTP
import Text.Regex.TDFA
import Text.Printf
getWordList :: IO String
getWordList = do
response <- simpleHTTP.getRequest$ url
getResponseBody response
where url = "http://wiki.puzzlers.org/pub/wordlists/unixdict.txt"
main = do
words <- getWordList
putStrLn "Checking Rule 1... |
Generate an equivalent Haskell version of this Python code. | import urllib.request
import re
PLAUSIBILITY_RATIO = 2
def plausibility_check(comment, x, y):
print('\n Checking plausibility of: %s' % comment)
if x > PLAUSIBILITY_RATIO * y:
print(' PLAUSIBLE. As we have counts of %i vs %i, a ratio of %4.1f times'
% (x, y, x / y))
else:
... | import Network.HTTP
import Text.Regex.TDFA
import Text.Printf
getWordList :: IO String
getWordList = do
response <- simpleHTTP.getRequest$ url
getResponseBody response
where url = "http://wiki.puzzlers.org/pub/wordlists/unixdict.txt"
main = do
words <- getWordList
putStrLn "Checking Rule 1... |
Change the following Python code into Haskell without altering its purpose. | import numpy as np
import matplotlib.pyplot as plt
def iterate(grid):
changed = False
for ii, arr in enumerate(grid):
for jj, val in enumerate(arr):
if val > 3:
grid[ii, jj] -= 4
if ii > 0:
grid[ii - 1, jj] += 1
if ii < le... |
module Rosetta.AbelianSandpileModel.ST
( simulate
, test
, toPGM
) where
import Control.Monad.Reader (asks, MonadReader (..), ReaderT, runReaderT)
import Control.Monad.ST (runST, ST)
import Control.Monad.State (evalStateT, forM_, lift, MonadState (..), StateT, modify, when)
import Data.Array.ST (f... |
Change the programming language of this snippet from Python to Haskell without modifying what it does. | import numpy as np
import matplotlib.pyplot as plt
def iterate(grid):
changed = False
for ii, arr in enumerate(grid):
for jj, val in enumerate(arr):
if val > 3:
grid[ii, jj] -= 4
if ii > 0:
grid[ii - 1, jj] += 1
if ii < le... |
module Rosetta.AbelianSandpileModel.ST
( simulate
, test
, toPGM
) where
import Control.Monad.Reader (asks, MonadReader (..), ReaderT, runReaderT)
import Control.Monad.ST (runST, ST)
import Control.Monad.State (evalStateT, forM_, lift, MonadState (..), StateT, modify, when)
import Data.Array.ST (f... |
Port the following code from Python to Haskell with equivalent syntax and logic. |
from __future__ import division
import sys
from PIL import Image
def _fpart(x):
return x - int(x)
def _rfpart(x):
return 1 - _fpart(x)
def putpixel(img, xy, color, alpha=1):
compose_color = lambda bg, fg: int(round(alpha * fg + (1-alpha) * bg))
c = compose_color(img.getpixel(xy), color)
i... |
module Main (main) where
import Codec.Picture (writePng)
import Codec.Picture.Types (Image, MutableImage(..), Pixel, PixelRGB8(..), createMutableImage, unsafeFreezeImage, writePixel)
import Control.Monad (void)
import Control.Monad.Primitive (PrimMonad, PrimState)
import Data.Foldable (foldlM)
type MImage m px = Mu... |
Write the same algorithm in Haskell as shown in this Python implementation. | def closest_more_than(n, lst):
"(index of) closest int from lst, to n that is also > n"
large = max(lst) + 1
return lst.index(min(lst, key=lambda x: (large if x <= n else x)))
def nexthigh(n):
"Return nxt highest number from n's digits using scan & re-order"
assert n == int(abs(n)), "n >= 0"
th... | import Data.List (nub, permutations, sort)
digitShuffleSuccessors :: Integer -> [Integer]
digitShuffleSuccessors n =
(fmap . (+) <*> (nub . sort . concatMap go . permutations . show)) n
where
go ds
| 0 >= delta = []
| otherwise = [delta]
where
delta = (read ds :: Integer) - n
main :... |
Produce a functionally identical Haskell code for the snippet given in Python. | def closest_more_than(n, lst):
"(index of) closest int from lst, to n that is also > n"
large = max(lst) + 1
return lst.index(min(lst, key=lambda x: (large if x <= n else x)))
def nexthigh(n):
"Return nxt highest number from n's digits using scan & re-order"
assert n == int(abs(n)), "n >= 0"
th... | import Data.List (nub, permutations, sort)
digitShuffleSuccessors :: Integer -> [Integer]
digitShuffleSuccessors n =
(fmap . (+) <*> (nub . sort . concatMap go . permutations . show)) n
where
go ds
| 0 >= delta = []
| otherwise = [delta]
where
delta = (read ds :: Integer) - n
main :... |
Ensure the translated Haskell code behaves exactly like the original Python snippet. | import random
from collections import OrderedDict
numbers = {
1: 'one',
2: 'two',
3: 'three',
4: 'four',
5: 'five',
6: 'six',
7: 'seven',
8: 'eight',
9: 'nine',
10: 'ten',
11: 'eleven',
12: 'twelve',
13: 'thirteen',
14: 'fourteen',
15: 'fifteen',
16: 's... | module Main where
import Data.List (find)
import Data.Char (toUpper)
firstNums :: [String]
firstNums =
[ "zero", "one", "two", "three", "four", "five", "six", "seven", "eight", "nine", "ten",
"eleven", "twelve", "thirteen", "fourteen", "fifteen", "sixteen", "seventeen", "eighteen", "nineteen"
]
tens :: [Stri... |
Generate an equivalent Haskell version of this Python code. | from turtle import *
import math
speed(0)
hideturtle()
part_ratio = 2 * math.cos(math.radians(72))
side_ratio = 1 / (part_ratio + 2)
hide_turtles = True
path_color = "black"
fill_color = "black"
def pentagon(t, s):
t.color(path_color, fill_color)
t.pendown()
t.right(36)
t.begin_fill()
for i... | import Graphics.Gloss
pentaflake :: Int -> Picture
pentaflake order = iterate transformation pentagon !! order
where
transformation = Scale s s . foldMap copy [0,72..288]
copy a = Rotate a . Translate 0 x
pentagon = Polygon [ (sin a, cos a) | a <- [0,2*pi/5..2*pi] ]
x = 2*cos(pi/5)
s = 1/(1+x)
... |
Convert this Python block to Haskell, preserving its control flow and logic. |
beforeTxt =
smallrc01 =
rc01 =
def intarray(binstring):
return [[1 if ch == '1' else 0 for ch in line]
for line in binstring.strip().split()]
def chararray(intmatrix):
return '\n'.join(''.join(str(p) for p in row) for row in intmatrix)
def toTxt(intmatrix):
Return 8-neighb... | import Data.Array
import qualified Data.List as List
data BW = Black | White
deriving (Eq, Show)
type Index = (Int, Int)
type BWArray = Array Index BW
toBW :: Char -> BW
toBW '0' = White
toBW '1' = Black
toBW ' ' = White
toBW '#' = Black
toBW _ = error "toBW: illegal char"
toBWArray :: [String] -> BWArray... |
Preserve the algorithm and functionality while converting the code from Python to Haskell. | >>> from itertools import permutations
>>> pieces = 'KQRrBbNN'
>>> starts = {''.join(p).upper() for p in permutations(pieces)
if p.index('B') % 2 != p.index('b') % 2
and ( p.index('r') < p.index('K') < p.index('R')
or p.index('R') < p.index('K') <... | import Data.List
import qualified Data.Set as Set
data Piece = K | Q | R | B | N deriving (Eq, Ord, Show)
isChess960 :: [Piece] -> Bool
isChess960 rank =
(odd . sum $ findIndices (== B) rank) && king > rookA && king < rookB
where
Just king = findIndex (== K) rank
[rookA, rookB] = findIndices (== R) r... |
Port the following code from Python to Haskell with equivalent syntax and logic. | irregularOrdinals = {
"one": "first",
"two": "second",
"three": "third",
"five": "fifth",
"eight": "eighth",
"nine": "ninth",
"twelve": "twelfth",
}
def num2ordinal(n):
conversion = int(float(n))
num = spell_integer(conversion)
hyphen = num.rsplit("-", 1)
num = num.rsplit(" ", 1)
... | spellOrdinal :: Integer -> String
spellOrdinal n
| n <= 0 = "not ordinal"
| n < 20 = small n
| n < 100 = case divMod n 10 of
(k, 0) -> spellInteger (10*k) ++ "th"
(k, m) -> spellInteger (10*k) ++ "-" ++ spellOrdinal m
| n < 1000 = case divMod n 100 of
(k, 0) -> spellInteger (100*k) ++ "th"
... |
Can you help me rewrite this code in Haskell instead of Python, keeping it the same logically? | from ipaddress import ip_address
from urllib.parse import urlparse
tests = [
"127.0.0.1",
"127.0.0.1:80",
"::1",
"[::1]:80",
"::192.168.0.1",
"2605:2700:0:3::4713:93e3",
"[2605:2700:0:3::4713:93e3]:80" ]
def parse_ip_port(netloc):
try:
ip = ip_address(netloc)
port = Non... | import Data.List (isInfixOf)
import Numeric (showHex)
import Data.Char (isDigit)
data IPChunk = IPv6Chunk String | IPv4Chunk (String, String) |
IPv6WithPort [IPChunk] String | IPv6NoPort [IPChunk] |
IPv4WithPort IPChunk String | IPv4NoPort IPChunk |
IPInvalid | IPZeroSection | IPUndefinedWithPort String |
... |
Port the provided Python code into Haskell while preserving the original functionality. | In [6]: def dec(n):
...: return len(n.rsplit('.')[-1]) if '.' in n else 0
In [7]: dec('12.345')
Out[7]: 3
In [8]: dec('12.3450')
Out[8]: 4
In [9]:
| decimal :: String -> Int
decimal [] = 0
decimal ('.':xs) = length xs
decimal (_:xs) = decimal xs
numDecimal :: Double -> Int
numDecimal = decimal . show
main = print . map numDecimal $ [12.0, 12.345, 12.3450, 12.345555555555, 12.34555555555555555555, 1.2345e+54]
|
Produce a functionally identical Haskell code for the snippet given in Python. | def min_cells_matrix(siz):
return [[min(row, col, siz - row - 1, siz - col - 1) for col in range(siz)] for row in range(siz)]
def display_matrix(mat):
siz = len(mat)
spaces = 2 if siz < 20 else 3 if siz < 200 else 4
print(f"\nMinimum number of cells after, before, above and below {siz} x {siz} square:"... | import Data.List.Split (chunksOf)
distancesToEdge :: Int -> [[Int]]
distancesToEdge n =
( \i ->
chunksOf n $
(\(x, y) -> minimum [x, y, i - x, i - y])
<$> (fmap (,) >>= (<*>)) [0 .. i]
)
$ pred n
main :: IO ()
main =
mapM_ putStrLn $
showMatrix . distancesToEdge <$> [10, 9, 2,... |
Change the programming language of this snippet from Python to Haskell without modifying what it does. |
def maxDeltas(ns):
pairs = [
(abs(a - b), (a, b)) for a, b
in zip(ns, ns[1:])
]
delta = max(pairs, key=lambda ab: ab[0])[0]
return [
ab for ab in pairs
if delta == ab[0]
]
def main():
maxPairs = maxDeltas([
1, 8, 2, -3, 0, 1, 1, -2.3, 0... | import Data.List (maximumBy)
import Data.Ord (comparing)
maxDeltas :: (Num a, Ord a) => [a] -> [(a, (a, a))]
maxDeltas xs = filter ((delta ==) . fst) pairs
where
pairs =
zipWith
(\a b -> (abs (a - b), (a, b)))
xs
(tail xs)
delta = fst $ maximumBy (comparing fst) pairs
main :: I... |
Port the provided Python code into Haskell while preserving the original functionality. | assert 1.008 == molar_mass('H')
assert 2.016 == molar_mass('H2')
assert 18.015 == molar_mass('H2O')
assert 34.014 == molar_mass('H2O2')
assert 34.014 == molar_mass('(HO)2')
assert 142.036 == molar_mass('Na2SO4')
assert ... | import Control.Monad (forM_)
import Control.Monad.Reader (Reader, ask, runReader)
import Data.Bifunctor (first)
import Data.Map (Map)
import qualified Data.Map as M
import Data.Void (Void)
import System.Environment (getArgs)
import System.IO (IOMode(ReadMode), withFile)
import System.IO.Strict (hGetContents)
import Tex... |
Preserve the algorithm and functionality while converting the code from Python to Haskell. | import operator
class AstNode(object):
def __init__( self, opr, left, right ):
self.opr = opr
self.l = left
self.r = right
def eval(self):
return self.opr(self.l.eval(), self.r.eval())
class LeafNode(object):
def __init__( self, valStrg ):
self.v = int(valStrg)
def eval(sel... |
import Text.Parsec
import Text.Parsec.Expr
import Text.Parsec.Combinator
import Data.Functor
import Data.Function (on)
data Exp
= Num Int
| Add Exp
Exp
| Sub Exp
Exp
| Mul Exp
Exp
| Div Exp
Exp
expr
:: Stream s m Char
=> ParsecT s u m Exp
expr = buildExpressionParser ta... |
Generate an equivalent Haskell version of this Python code. | import operator
class AstNode(object):
def __init__( self, opr, left, right ):
self.opr = opr
self.l = left
self.r = right
def eval(self):
return self.opr(self.l.eval(), self.r.eval())
class LeafNode(object):
def __init__( self, valStrg ):
self.v = int(valStrg)
def eval(sel... |
import Text.Parsec
import Text.Parsec.Expr
import Text.Parsec.Combinator
import Data.Functor
import Data.Function (on)
data Exp
= Num Int
| Add Exp
Exp
| Sub Exp
Exp
| Mul Exp
Exp
| Div Exp
Exp
expr
:: Stream s m Char
=> ParsecT s u m Exp
expr = buildExpressionParser ta... |
Change the programming language of this snippet from Python to Haskell without modifying what it does. | from collections import defaultdict
rep = {'a' : {1 : 'A', 2 : 'B', 4 : 'C', 5 : 'D'}, 'b' : {1 : 'E'}, 'r' : {2 : 'F'}}
def trstring(oldstring, repdict):
seen, newchars = defaultdict(lambda:1, {}), []
for c in oldstring:
i = seen[c]
newchars.append(repdict[c][i] if c in repdict and i in repd... | import Data.List (mapAccumL)
import qualified Data.Map.Strict as M
import Data.Maybe (fromMaybe)
nthCharsReplaced :: M.Map Char [Maybe Char] -> String -> String
nthCharsReplaced ruleMap = snd . mapAccumL go ruleMap
where
go a c =
case M.lookup c a of
Nothing -> (a, c)
Just [] -> (a, c)
... |
Can you help me rewrite this code in Haskell instead of Python, keeping it the same logically? | from collections import defaultdict
rep = {'a' : {1 : 'A', 2 : 'B', 4 : 'C', 5 : 'D'}, 'b' : {1 : 'E'}, 'r' : {2 : 'F'}}
def trstring(oldstring, repdict):
seen, newchars = defaultdict(lambda:1, {}), []
for c in oldstring:
i = seen[c]
newchars.append(repdict[c][i] if c in repdict and i in repd... | import Data.List (mapAccumL)
import qualified Data.Map.Strict as M
import Data.Maybe (fromMaybe)
nthCharsReplaced :: M.Map Char [Maybe Char] -> String -> String
nthCharsReplaced ruleMap = snd . mapAccumL go ruleMap
where
go a c =
case M.lookup c a of
Nothing -> (a, c)
Just [] -> (a, c)
... |
Write a version of this Python function in Haskell with identical behavior. | import sys
import pygame
pygame.init()
clk = pygame.time.Clock()
if pygame.joystick.get_count() == 0:
raise IOError("No joystick detected")
joy = pygame.joystick.Joystick(0)
joy.init()
size = width, height = 600, 600
screen = pygame.display.set_mode(size)
pygame.display.set_caption("Joystick Tester")
frame... | import qualified Graphics.UI.GLFW as GLFW
import Graphics.Win32.Key
import Control.Monad.RWS.Strict (liftIO)
main = do
liftIO $ do
_ <- GLFW.init
GLFW.pollEvents
(jxrot, jyrot) <- liftIO $ getJoystickDirections GLFW.Joystick'1
putStrLn $ (show jxrot) ++ " " ++ (show jyrot)... |
Produce a language-to-language conversion: from Python to Haskell, same semantics. | from pprint import pprint as pp
class Template():
def __init__(self, structure):
self.structure = structure
self.used_payloads, self.missed_payloads = [], []
def inject_payload(self, id2data):
def _inject_payload(substruct, i2d, used, missed):
used.extend(i2d[x... |
data Template a = Val a | List [Template a]
deriving ( Show
, Functor
, Foldable
, Traversable )
|
Convert this Python block to Haskell, preserving its control flow and logic. |
from itertools import chain, product, takewhile, tee
from functools import cmp_to_key, reduce
def sortedOutline(cmp):
def go(outlineText):
indentTuples = indentTextPairs(
outlineText.splitlines()
)
return bindLR(
minimumIndent(enumerate(indentTuples))
... |
import Data.Tree (Tree(..), foldTree)
import qualified Data.Text.IO as T
import qualified Data.Text as T
import qualified Data.List as L
import Data.Bifunctor (first)
import Data.Ord (comparing)
import Data.Char (isSpace)
sortedOutline :: (Tree T.Text -> Tree T.Text -> Ordering)
-> T.Text
... |
Write a version of this Python function in Haskell with identical behavior. |
import itertools
import re
import sys
from collections import deque
from typing import NamedTuple
RE_OUTLINE = re.compile(r"^((?: |\t)*)(.+)$", re.M)
COLORS = itertools.cycle(
[
"
"
"
"
"
]
)
class Node:
def __init__(self, indent, value, parent, children=None)... |
module OutlineTree where
import Data.Bifunctor (first)
import Data.Bool (bool)
import Data.Char (isSpace)
import Data.List (find, intercalate)
import Data.Tree (Tree (..), foldTree, levels)
wikiTablesFromOutline :: [String] -> String -> String
wikiTablesFromOutline colorSwatch outline =
intercalate "\n\n" $
... |
Produce a language-to-language conversion: from Python to Haskell, same semantics. |
from math import gcd
from functools import reduce
def lcm(a, b):
return 0 if 0 == a or 0 == b else (
abs(a * b) // gcd(a, b)
)
for i in [10, 20, 200, 2000]:
print(str(i) + ':', reduce(lcm, range(1, i + 1)))
| import Text.Printf (printf)
smallest :: Integer -> Integer
smallest =
foldr lcm 1 . enumFromTo 1
main :: IO ()
main =
(putStrLn . unlines) $
showSmallest <$> [10, 20, 200, 2000]
showSmallest :: Integer -> String
showSmallest =
((<>) . (<> " -> ") . printf "%4d")
<*> (printf "%d" . smallest)
|
Rewrite the snippet below in Haskell so it works the same as the original Python code. |
from itertools import count
def firstGap(xs):
return next(x for x in count(1) if x not in xs)
def main():
print('\n'.join([
f'{repr(xs)} -> {firstGap(xs)}' for xs in [
[1, 2, 0],
[3, 4, -1, 1],
[7, 8, 9, 11, 12]
]
]))
if __name__ == '... | import Data.List (sort)
task :: Integral a => [a] -> a
task = go . (0 :) . sort . filter (> 0)
where
go [x] = succ x
go (w : xs@(x : _))
| x == succ w = go xs
| otherwise = succ w
main :: IO ()
main =
print $
map
task
[[1, 2, 0], [3, 4, -1, 1], [7, 8, 9, 11, 12]]
|
Maintain the same structure and functionality when rewriting this code in Haskell. | import math
print("working...")
limit = 1000000
Primes = []
oldPrime = 0
newPrime = 0
x = 0
def isPrime(n):
for i in range(2,int(n**0.5)+1):
if n%i==0:
return False
return True
def issquare(x):
for n in range(x):
if (x == n*n):
return 1
return 0
for n in range(limit):
if isPrim... | import Data.List.Split ( divvy )
isSquare :: Int -> Bool
isSquare n = (snd $ properFraction $ sqrt $ fromIntegral n) == 0.0
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 $ from... |
Port the provided Python code into Haskell while preserving the original functionality. | import math
print("working...")
limit = 1000000
Primes = []
oldPrime = 0
newPrime = 0
x = 0
def isPrime(n):
for i in range(2,int(n**0.5)+1):
if n%i==0:
return False
return True
def issquare(x):
for n in range(x):
if (x == n*n):
return 1
return 0
for n in range(limit):
if isPrim... | import Data.List.Split ( divvy )
isSquare :: Int -> Bool
isSquare n = (snd $ properFraction $ sqrt $ fromIntegral n) == 0.0
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 $ from... |
Produce a language-to-language conversion: from Python to Haskell, same semantics. | from fractions import Fraction
class Fr(Fraction):
def __repr__(self):
return '(%s/%s)' % (self.numerator, self.denominator)
def farey(n, length=False):
if not length:
return [Fr(0, 1)] + sorted({Fr(m, k) for k in range(1, n+1) for m in range(1, k+1)})
else:
return (n*(... | import Data.List (unfoldr, mapAccumR)
import Data.Ratio ((%), denominator, numerator)
import Text.Printf (PrintfArg, printf)
farey :: Integer -> [Rational]
farey n = 0 : unfoldr step (0, 1, 1, n)
where
step (a, b, c, d)
| c > n = Nothing
| otherwise =
let k = (n + b) `quot` d
in Just... |
Can you help me rewrite this code in Haskell instead of Python, keeping it the same logically? | from fractions import Fraction
class Fr(Fraction):
def __repr__(self):
return '(%s/%s)' % (self.numerator, self.denominator)
def farey(n, length=False):
if not length:
return [Fr(0, 1)] + sorted({Fr(m, k) for k in range(1, n+1) for m in range(1, k+1)})
else:
return (n*(... | import Data.List (unfoldr, mapAccumR)
import Data.Ratio ((%), denominator, numerator)
import Text.Printf (PrintfArg, printf)
farey :: Integer -> [Rational]
farey n = 0 : unfoldr step (0, 1, 1, n)
where
step (a, b, c, d)
| c > n = Nothing
| otherwise =
let k = (n + b) `quot` d
in Just... |
Translate the given Python code snippet into Haskell without altering its behavior. | from proper_divisors import proper_divs
from functools import lru_cache
@lru_cache()
def pdsum(n):
return sum(proper_divs(n))
def aliquot(n, maxlen=16, maxterm=2**47):
if n == 0:
return 'terminating', [0]
s, slen, new = [n], 1, n
while slen <= maxlen and new < maxterm:
new =... | divisors :: (Integral a) => a -> [a]
divisors n = filter ((0 ==) . (n `mod`)) [1 .. (n `div` 2)]
data Class
= Terminating
| Perfect
| Amicable
| Sociable
| Aspiring
| Cyclic
| Nonterminating
deriving (Show)
aliquot :: (Integral a) => a -> [a]
aliquot 0 = [0]
aliquot n = n : (aliquot $ sum $ divisors n... |
Translate the given Python code snippet into Haskell without altering its behavior. | from proper_divisors import proper_divs
from functools import lru_cache
@lru_cache()
def pdsum(n):
return sum(proper_divs(n))
def aliquot(n, maxlen=16, maxterm=2**47):
if n == 0:
return 'terminating', [0]
s, slen, new = [n], 1, n
while slen <= maxlen and new < maxterm:
new =... | divisors :: (Integral a) => a -> [a]
divisors n = filter ((0 ==) . (n `mod`)) [1 .. (n `div` 2)]
data Class
= Terminating
| Perfect
| Amicable
| Sociable
| Aspiring
| Cyclic
| Nonterminating
deriving (Show)
aliquot :: (Integral a) => a -> [a]
aliquot 0 = [0]
aliquot n = n : (aliquot $ sum $ divisors n... |
Generate a Haskell translation of this Python snippet without changing its computational steps. | import random
def MillerRabinPrimalityTest(number):
if number == 2:
return True
elif number == 1 or number % 2 == 0:
return False
oddPartOfNumber = number - 1
timesTwoDividNumber = 0
while oddPartOfNumber % 2 == 0:
oddPartOfNumbe... | import Data.Numbers.Primes (primes)
import Text.Printf (printf)
lucasLehmer :: Int -> Bool
lucasLehmer p = iterate f 4 !! p-2 == 0
where
f b = (b^2 - 2) `mod` m
m = 2^p - 1
main = mapM_ (printf "M %d\n") $ take 20 mersenne
where
mersenne = filter lucasLehmer primes
|
Convert the following code from Python to Haskell, ensuring the logic remains intact. | import random
def MillerRabinPrimalityTest(number):
if number == 2:
return True
elif number == 1 or number % 2 == 0:
return False
oddPartOfNumber = number - 1
timesTwoDividNumber = 0
while oddPartOfNumber % 2 == 0:
oddPartOfNumbe... | import Data.Numbers.Primes (primes)
import Text.Printf (printf)
lucasLehmer :: Int -> Bool
lucasLehmer p = iterate f 4 !! p-2 == 0
where
f b = (b^2 - 2) `mod` m
m = 2^p - 1
main = mapM_ (printf "M %d\n") $ take 20 mersenne
where
mersenne = filter lucasLehmer primes
|
Preserve the algorithm and functionality while converting the code from Python to Haskell. | LIMIT = 1_000_035
def primes2(limit=LIMIT):
if limit < 2: return []
if limit < 3: return [2]
lmtbf = (limit - 3) // 2
buf = [True] * (lmtbf + 1)
for i in range((int(limit ** 0.5) - 3) // 2 + 1):
if buf[i]:
p = i + i + 3
s = p * (i + 1) + i
buf[s::p] = [Fal... | import Text.Printf (printf)
import Data.Numbers.Primes (isPrime, primes)
type Pair = (Int, Int)
type Triplet = (Int, Int, Int)
type Quad = (Int, Int, Int, Int)
type Quin = (Int, Int, Int, Int, Int)
type Result = ([Pair], [Triplet], [Quad], [Quin], [Int])
groups :: Int -> Result -> Result
groups n r@(p, t, q,... |
Translate the given Python code snippet into Haskell without altering its behavior. | def KlarnerRado(N):
K = [1]
for i in range(N):
j = K[i]
firstadd, secondadd = 2 * j + 1, 3 * j + 1
if firstadd < K[-1]:
for pos in range(len(K)-1, 1, -1):
if K[pos] < firstadd < K[pos + 1]:
K.insert(pos + 1, firstadd)
br... | import Data.List (intercalate)
import Data.List.Ordered (union)
import Data.List.Split (chunksOf)
import Text.Printf (printf)
klarnerRado :: [Integer]
klarnerRado =
1 :
union
(succ . (2 *) <$> klarnerRado)
(succ . (3 *) <$> klarnerRado)
main :: IO ()
main = do
putStrLn "First one hundred elements... |
Generate a Haskell translation of this Python snippet without changing its computational steps. | def KlarnerRado(N):
K = [1]
for i in range(N):
j = K[i]
firstadd, secondadd = 2 * j + 1, 3 * j + 1
if firstadd < K[-1]:
for pos in range(len(K)-1, 1, -1):
if K[pos] < firstadd < K[pos + 1]:
K.insert(pos + 1, firstadd)
br... | import Data.List (intercalate)
import Data.List.Ordered (union)
import Data.List.Split (chunksOf)
import Text.Printf (printf)
klarnerRado :: [Integer]
klarnerRado =
1 :
union
(succ . (2 *) <$> klarnerRado)
(succ . (3 *) <$> klarnerRado)
main :: IO ()
main = do
putStrLn "First one hundred elements... |
Ensure the translated Haskell code behaves exactly like the original Python snippet. | from collections import defaultdict
from itertools import product
from pprint import pprint as pp
cube2n = {x**3:x for x in range(1, 1201)}
sum2cubes = defaultdict(set)
for c1, c2 in product(cube2n, cube2n):
if c1 >= c2: sum2cubes[c1 + c2].add((cube2n[c1], cube2n[c2]))
taxied = sorted((k, v) for k,v in sum2cubes.it... | import Data.List (groupBy, sortOn, tails, transpose)
import Data.Function (on)
taxis :: Int -> [[(Int, ((Int, Int), (Int, Int)))]]
taxis nCubes =
filter ((> 1) . length) $
groupBy (on (==) fst) $
sortOn fst
[ (fst x + fst y, (x, y))
| (x:t) <- tails $ ((^ 3) >>= (,)) <$> [1 .. nCubes]
, y <- t ]
... |
Rewrite the snippet below in Haskell so it works the same as the original Python code. | import numpy as np
def primesfrom2to(n):
sieve = np.ones(n//3 + (n%6==2), dtype=np.bool)
sieve[0] = False
for i in range(int(n**0.5)//3+1):
if sieve[i]:
k=3*i+1|1
sieve[ ((k*k)//3) ::2*k] = False
sieve[(k*k+4*k-2*k*(i&1))//3::2*k] = False
... | import Text.Printf (printf)
import Data.Numbers.Primes (primes)
xPrimes :: (Real a, Fractional b) => (b -> b -> Bool) -> [a] -> [a]
xPrimes op ps@(p1:p2:p3:xs)
| realToFrac p2 `op` (realToFrac (p1 + p3) / 2) = p2 : xPrimes op (tail ps)
| otherwise = xPrimes op (tail ps)
main :: IO ()
main = do
printf "First 36... |
Write the same algorithm in Haskell as shown in this Python implementation. | from itertools import islice
def lfact():
yield 0
fact, summ, n = 1, 0, 1
while 1:
fact, summ, n = fact*n, summ + fact, n + 1
yield summ
print('first 11:\n %r' % [lf for i, lf in zip(range(11), lfact())])
print('20 through 110 (inclusive) by tens:')
for lf in islice(lfact(), 20, 111, 10)... | leftFact :: [Integer]
leftFact = scanl (+) 0 fact
fact :: [Integer]
fact = scanl (*) 1 [1 ..]
main :: IO ()
main =
mapM_
putStrLn
[ "0 ~ 10:"
, show $ (leftFact !!) <$> [0 .. 10]
, ""
, "20 ~ 110 by tens:"
, unlines $ show . (leftFact !!) <$> [20,30 .. 110]
, ""
, "length of 1,000 ~ ... |
Change the following Python code into Haskell without altering its purpose. | from itertools import islice
def lfact():
yield 0
fact, summ, n = 1, 0, 1
while 1:
fact, summ, n = fact*n, summ + fact, n + 1
yield summ
print('first 11:\n %r' % [lf for i, lf in zip(range(11), lfact())])
print('20 through 110 (inclusive) by tens:')
for lf in islice(lfact(), 20, 111, 10)... | leftFact :: [Integer]
leftFact = scanl (+) 0 fact
fact :: [Integer]
fact = scanl (*) 1 [1 ..]
main :: IO ()
main =
mapM_
putStrLn
[ "0 ~ 10:"
, show $ (leftFact !!) <$> [0 .. 10]
, ""
, "20 ~ 110 by tens:"
, unlines $ show . (leftFact !!) <$> [20,30 .. 110]
, ""
, "length of 1,000 ~ ... |
Transform the following Python implementation into Haskell, maintaining the same output and logic. |
from sympy import isprime
def motzkin(num_wanted):
mot = [1] * (num_wanted + 1)
for i in range(2, num_wanted + 1):
mot[i] = (mot[i-1]*(2*i+1) + mot[i-2]*(3*i-3)) // (i + 2)
return mot
def print_motzkin_table(N=41):
print(
" n M[n] Prime?\n------------... | import Control.Monad.Memo (Memo, memo, startEvalMemo)
import Math.NumberTheory.Primes.Testing (isPrime)
import System.Environment (getArgs)
import Text.Printf (printf)
type I = Integer
motzkin :: I -> Memo I I I
motzkin 0 = return 1
motzkin 1 = return 1
motzkin n = do
m1 <- memo motzkin (n-1)
m2 <- memo motzkin... |
Produce a functionally identical Haskell code for the snippet given in Python. | Python 3.8.5 (default, Sep 3 2020, 21:29:08) [MSC v.1916 64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license()" for more information.
>>> from sympy import isprime
>>> [x for x in range(101,500)
if isprime(sum(int(c) for c in str(x)[:2])) and
isprime(sum(int(c) for c in str(x)[1:]))]
[111, ... | import Data.List (intercalate)
import Data.List.Split (chunksOf)
isStrangePlus :: Int -> Bool
isStrangePlus n =
all
(\(a, b) -> (a + b) `elem` [2, 3, 5, 7, 11, 13, 17])
$ (zip <*> tail) (digits n)
digits :: Int -> [Int]
digits = fmap (read . return) . show
main =
let xs = filter isStrangePlus [100 ..... |
Convert the following code from Python to Haskell, ensuring the logic remains intact. | Python 3.8.5 (default, Sep 3 2020, 21:29:08) [MSC v.1916 64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license()" for more information.
>>> from sympy import isprime
>>> [x for x in range(101,500)
if isprime(sum(int(c) for c in str(x)[:2])) and
isprime(sum(int(c) for c in str(x)[1:]))]
[111, ... | import Data.List (intercalate)
import Data.List.Split (chunksOf)
isStrangePlus :: Int -> Bool
isStrangePlus n =
all
(\(a, b) -> (a + b) `elem` [2, 3, 5, 7, 11, 13, 17])
$ (zip <*> tail) (digits n)
digits :: Int -> [Int]
digits = fmap (read . return) . show
main =
let xs = filter isStrangePlus [100 ..... |
Write the same algorithm in Haskell as shown in this Python implementation. | 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 digit_check(n):
if len(str(n))<2:
return... |
import Control.Monad (guard)
import Math.NumberTheory.Primes.Testing (isPrime)
import Data.List.Split (chunksOf)
import Data.List (intercalate)
import Text.Printf (printf)
smarandache :: [Integer]
smarandache = [2,3,5,7] <> s [2,3,5,7] >>= \x -> guard (isPrime x) >> [x]
where s xs = r <> s r where r = xs >>= \x -> [... |
Port the provided Python code into Haskell while preserving the original functionality. | def MagicSquareDoublyEven(order):
sq = [range(1+n*order,order + (n*order)+1) for n in range(order) ]
n1 = order/4
for r in range(n1):
r1 = sq[r][n1:-n1]
r2 = sq[order -r - 1][n1:-n1]
r1.reverse()
r2.reverse()
sq[r][n1:-n1] = r2
sq[order -r - 1][n1:-n1] = r1
... | import Data.List (transpose, unfoldr, intercalate)
import Data.List.Split (chunksOf)
import Data.Bool (bool)
import Control.Monad (forM_)
magicSquare :: Int -> [[Int]]
magicSquare n
| rem n 4 > 0 = []
| otherwise =
chunksOf n $ zipWith (flip (bool =<< (-) limit)) series [1 .. sqr]
where
sqr = n * n
l... |
Rewrite the snippet below in Haskell so it works the same as the original Python code. | import math
def SquareFree ( _number ) :
max = (int) (math.sqrt ( _number ))
for root in range ( 2, max+1 ):
if 0 == _number % ( root * root ):
return False
return True
def ListSquareFrees( _start, _end ):
count = 0
for i in range ( _start, _end+1 ):
if True == SquareFree( i ):
print ( "{}\t".fo... | import Data.List.Split (chunksOf)
import Math.NumberTheory.Primes (factorise)
import Text.Printf (printf)
isSquareFree :: Integer -> Bool
isSquareFree = all ((== 1) . snd) . factorise
squareFrees :: Integer -> Integer -> [Integer]
squareFrees lo hi = filter isSquareFree [lo..hi]
counts :: (Ord a, Num b) => [a] ... |
Change the programming language of this snippet from Python to Haskell without modifying what it does. | class DigitSumer :
def __init__(self):
sumdigit = lambda n : sum( map( int,str( n )))
self.t = [sumdigit( i ) for i in xrange( 10000 )]
def __call__ ( self,n ):
r = 0
while n >= 10000 :
n,q = divmod( n,10000 )
r += self.t[q]
return r + self.t[n]
... | import Control.Monad (forM_)
import Text.Printf
selfs :: [Integer]
selfs = sieve (sumFs [0..]) [0..]
where
sumFs = zipWith (+) [ a+b+c+d+e+f+g+h+i+j
| a <- [0..9] , b <- [0..9]
, c <- [0..9] , d <- [0..9]
, e <- [0..9] , f <- [0..9]
... |
Convert this Python snippet to Haskell and keep its semantics consistent. |
def digit_sum(n, sum):
sum += 1
while n > 0 and n % 10 == 0:
sum -= 9
n /= 10
return sum
previous = 1
gap = 0
sum = 0
niven_index = 0
gap_index = 1
print("Gap index Gap Niven index Niven number")
niven = 1
while gap_index <= 22:
sum = digit_sum(niven, sum)
... |
import Control.Monad (guard)
import Text.Printf (printf)
import Data.List (intercalate, unfoldr)
import Data.List.Split (chunksOf)
import Data.Tuple (swap)
nivens :: [Int]
nivens = [1..] >>= \n -> guard (n `rem` digitSum n == 0) >> [n]
where
digitSum = sum . unfoldr (\x -> guard (x > 0) >> pure (swap $ x `quotRem`... |
Generate a Haskell translation of this Python snippet without changing its computational steps. | from sys import argv
unit2mult = {"arshin": 0.7112, "centimeter": 0.01, "diuym": 0.0254,
"fut": 0.3048, "kilometer": 1000.0, "liniya": 0.00254,
"meter": 1.0, "milia": 7467.6, "piad": 0.1778,
"sazhen": 2.1336, "tochka": 0.000254, "vershok": 0.04445,... | module Main where
import Text.Printf (printf)
import System.Environment (getArgs, getProgName)
tochka = ("tochka" , 0.000254)
liniya = ("liniya" , 0.00254)
centimeter = ("centimeter", 0.01)
diuym = ("diuym" , 0.0254)
vershok = ("vershok" , 0.04445)
piad = ("piad" , 0.1778)
fut ... |
Rewrite this program in Haskell while keeping its functionality equivalent to the Python version. |
from itertools import count, islice
def a131382():
return (
elemIndex(x)(
productDigitSums(x)
) for x in count(1)
)
def productDigitSums(n):
return (digitSum(n * x) for x in count(0))
def main():
print(
table(10)([
str(x) for x ... | import Data.Bifunctor (first)
import Data.List (elemIndex, intercalate, transpose)
import Data.List.Split (chunksOf)
import Data.Maybe (fromJust)
import Text.Printf (printf)
a131382 :: [Int]
a131382 =
fromJust . (elemIndex <*> productDigitSums)
<$> [1 ..]
productDigitSums :: Int -> [Int]
productDigitSums n = ... |
Produce a functionally identical Haskell code for the snippet given in Python. | def quad(top=2200):
r = [False] * top
ab = [False] * (top * 2)**2
for a in range(1, top):
for b in range(a, top):
ab[a * a + b * b] = True
s = 3
for c in range(1, top):
s1, s, s2 = s, s + 2, s + 2
for d in range(c + 1, top):
if ab[s1]:
... | powersOfTwo :: [Int]
powersOfTwo = iterate (2 *) 1
unrepresentable :: [Int]
unrepresentable = merge powersOfTwo ((5 *) <$> powersOfTwo)
merge :: [Int] -> [Int] -> [Int]
merge xxs@(x:xs) yys@(y:ys)
| x < y = x : merge xs yys
| otherwise = y : merge xxs ys
main :: IO ()
main = do
putStrLn "The values of d <= 220... |
Generate an equivalent Haskell version of this Python code. |
from collections import Counter
def decompose_sum(s):
return [(a,s-a) for a in range(2,int(s/2+1))]
all_pairs = set((a,b) for a in range(2,100) for b in range(a+1,100) if a+b<100)
product_counts = Counter(c*d for c,d in all_pairs)
unique_products = set((a,b) for a,b in all_pairs if product_counts[a*b]==1)
s_... | import Data.List (intersect)
s1, s2, s3, s4 :: [(Int, Int)]
s1 = [(x, y) | x <- [1 .. 100], y <- [1 .. 100], 1 < x && x < y && x + y < 100]
add, mul :: (Int, Int) -> Int
add (x, y) = x + y
mul (x, y) = x * y
sumEq, mulEq :: (Int, Int) -> [(Int, Int)]
sumEq p = filter (\q -> add q == add p) s1
mulEq p = filter (\q ->... |
Write a version of this Python function in Haskell with identical behavior. | >>> def isint(f):
return complex(f).imag == 0 and complex(f).real.is_integer()
>>> [isint(f) for f in (1.0, 2, (3.0+0.0j), 4.1, (3+4j), (5.6+0j))]
[True, True, True, False, False, False]
>>>
...
>>> isint(25.000000)
True
>>> isint(24.999999)
False
>>> isint(25.000100)
False
>>> isint(-2.1e120)
True
>>> isint(-5... | import Data.Decimal
import Data.Ratio
import Data.Complex
|
Translate this program into Haskell but keep the logic exactly as in Python. |
def isPrime(n):
for i in range(2, int(n**0.5) + 1):
if n % i == 0:
return False
return True
if __name__ == "__main__":
n = 0
num = 0
print('The first 20 pairs of numbers whose sum is prime:')
while True:
n += 1
suma = 2*n+1
if isPrime(suma... | import Data.Numbers.Primes
primeSumsOfConsecutiveNumbers :: Integral a => [(a, (a, a))]
primeSumsOfConsecutiveNumbers =
let go a b = [(n, (a, b)) | let n = a + b, isPrime n]
in concat $ zipWith go [1 ..] [2 ..]
main :: IO ()
main = mapM_ print $ take 20 primeSumsOfConsecutiveNumbers
|
Write the same algorithm in Haskell as shown in this Python implementation. | from __future__ import print_function
from time import sleep
last_idle = last_total = 0
while True:
with open('/proc/stat') as f:
fields = [float(column) for column in f.readline().strip().split()[1:]]
idle, total = fields[3], sum(fields)
idle_delta, total_delta = idle - last_idle, total - last_to... | import Data.List ( (!!) )
splitString :: Char -> String -> [String]
splitString c [] = []
splitString c s = let ( item , rest ) = break ( == c ) s
( _ , next ) = break ( /= c ) rest
in item : splitString c next
computeUsage :: String -> Double
computeUsage s = (1.0 - ((lineElements ... |
Translate this program into Haskell but keep the logic exactly as in Python. | import time
def ulam(n):
if n <= 2:
return n
mx = 1352000
lst = [1, 2] + [0] * mx
sums = [0] * (mx * 2 + 1)
sums[3] = 1
size = 2
while size < n:
query = lst[size-1] + 1
while True:
if sums[query] == 1:
for i in range(size):
... | import Data.List
ulam
:: Integral i =>
Int -> i
ulam 1 = 1
ulam 2 = 2
ulam n
| n > 2 = ulams !! (n-1)
ulams
:: Integral n =>
[n]
ulams = 1:2:(nexts [2,1])
nexts us = u: (nexts (u:us))
where
n = length us
[u] = head . filter isSingleton . group . sort $
[v | i <- [0 .. n-2], j ... |
Write the same code in Haskell as shown below in Python. | def smallest_six(n):
p = 1
while str(n) not in str(p): p *= 6
return p
for n in range(22):
print("{:2}: {}".format(n, smallest_six(n)))
| import Data.List (find, isInfixOf)
import Text.Printf (printf)
smallest :: Integer -> Integer
smallest n = d
where
Just d = find ((show n `isInfixOf`) . show) sixes
sixes :: [Integer]
sixes = iterate (* 6) 1
main :: IO ()
main =
putStr $
[0 .. 21] >>= printf "%2d: %d\n" <*> smallest
|
Generate an equivalent Haskell version of this Python code. |
def isPrime(n):
for i in range(2, int(n**0.5) + 1):
if n % i == 0:
return False
return True
if __name__ == '__main__':
suma = 2
n = 1
for i in range(3, 2000000, 2):
if isPrime(i):
suma += i
n+=1
print(suma)
| import Data.Numbers.Primes (primes)
sumOfPrimesBelow :: Integral a => a -> a
sumOfPrimesBelow n =
sum $ takeWhile (< n) primes
main :: IO ()
main = print $ sumOfPrimesBelow 2000000
|
Port the following code from Python to Haskell with equivalent syntax and logic. | print("working...")
print("Steady squares under 10.000 are:")
limit = 10000
for n in range(1,limit):
nstr = str(n)
nlen = len(nstr)
square = str(pow(n,2))
rn = square[-nlen:]
if nstr == rn:
print(str(n) + " " + str(square))
print("done...")
| import Control.Monad (join)
import Data.List (isSuffixOf)
p :: Int -> Bool
p = isSuffixOf . show <*> (show . join (*))
main :: IO ()
main =
print $
takeWhile (< 10000) $ filter p [0 ..]
|
Write the same algorithm in Haskell as shown in this Python implementation. | primes =[]
sp =[]
usp=[]
n = 10000000
if 2<n:
primes.append(2)
for i in range(3,n+1,2):
for j in primes:
if(j>i/2) or (j==primes[-1]):
primes.append(i)
if((i-1)/2) in primes:
sp.append(i)
break
else:
usp.append(i)
... | import Text.Printf (printf)
import Data.Numbers.Primes (isPrime, primes)
main = do
printf "First 35 safe primes: %s\n" (show $ take 35 safe)
printf "There are %d safe primes below 100,000.\n" (length $ takeWhile (<1000000) safe)
printf "There are %d safe primes below 10,000,000.\n\n" (length $ takeWhile (<10000... |
Convert this Python block to Haskell, preserving its control flow and logic. | from collections import defaultdict
def hashJoin(table1, index1, table2, index2):
h = defaultdict(list)
for s in table1:
h[s[index1]].append(s)
return [(s, r) for r in table2 for s in h[r[index2]]]
table1 = [(27, "Jonah"),
(18, "Alan"),
(28, "Glory"),
(18, "... |
import qualified Data.HashTable.ST.Basic as H
import Data.Hashable
import Control.Monad.ST
import Control.Monad
import Data.STRef
hashJoin :: (Eq k, Hashable k) =>
[t] -> (t -> k) -> [a] -> (a -> k) -> [(t, a)]
hashJoin xs fx ys fy = runST $ do
l <- newSTRef []
ht <- H.new
forM_ ys $ \y -> H.insert ... |
Write a version of this Python function in Haskell with identical behavior. |
from math import sqrt
def isGiuga(m):
n = m
f = 2
l = sqrt(n)
while True:
if n % f == 0:
if ((m / f) - 1) % f != 0:
return False
n /= f
if f > n:
return True
else:
f += 1
if f > l:
... |
primeFactors :: Int -> [Int]
primeFactors n = snd $ until ( (== 1) . fst ) step (n , [] )
where
step :: (Int , [Int] ) -> (Int , [Int] )
step (n , li) = ( div n h , li ++ [h] )
where
h :: Int
h = head $ tail $ divisors n
divisors :: Int -> [Int]
divisors n = [d | d <- [1 .. n] , mod n d == 0]
isGiu... |
Maintain the same structure and functionality when rewriting this code in 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])
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.