将列表拆分为奇数和偶数 (Haskell)
Splitting list into odd and even (Haskell)
我需要创建一个函数,它将接受一个整数列表并将它们分成 2 个列表,一个是奇数,另一个是偶数
split :: [a] -> ([a], [a])
split = undefined
上面是函数基线,下面是我目前的尝试
split :: [a] -> ([a], [a])
split [] = ([],[])
split (x:xs) | x mod 2 == 0 = ([],[x:split xs])
| x mod 2 /= 0 = ([x:split xs],[])
| otherwise = ([],[])
显式递归:
split :: Integral a => [a] -> ([a], [a])
split [] = ([], [])
split (x:xs)
| even x = (x:ys, zs)
| otherwise = (ys, x:zs)
where
(ys, zs) = split xs
隐式递归:
splitf :: Integral a => [a] -> ([a], [a])
splitf xs = foldr (\x (ys, zs) -> if even x then (x:ys, zs) else (ys, x:zs))
([], []) xs
您可以将其简化为无点样式:
splitf2 :: Integral a => [a] -> ([a], [a])
splitf2 = foldr (\x (ys, zs) -> if even x then (x:ys, zs) else (ys, x:zs))
([], [])
我认为代码是不言自明的。如果有什么需要我进一步解释的,请告诉我。
我需要创建一个函数,它将接受一个整数列表并将它们分成 2 个列表,一个是奇数,另一个是偶数
split :: [a] -> ([a], [a])
split = undefined
上面是函数基线,下面是我目前的尝试
split :: [a] -> ([a], [a])
split [] = ([],[])
split (x:xs) | x mod 2 == 0 = ([],[x:split xs])
| x mod 2 /= 0 = ([x:split xs],[])
| otherwise = ([],[])
显式递归:
split :: Integral a => [a] -> ([a], [a])
split [] = ([], [])
split (x:xs)
| even x = (x:ys, zs)
| otherwise = (ys, x:zs)
where
(ys, zs) = split xs
隐式递归:
splitf :: Integral a => [a] -> ([a], [a])
splitf xs = foldr (\x (ys, zs) -> if even x then (x:ys, zs) else (ys, x:zs))
([], []) xs
您可以将其简化为无点样式:
splitf2 :: Integral a => [a] -> ([a], [a])
splitf2 = foldr (\x (ys, zs) -> if even x then (x:ys, zs) else (ys, x:zs))
([], [])
我认为代码是不言自明的。如果有什么需要我进一步解释的,请告诉我。