代码之家  ›  专栏  ›  技术社区  ›  Matt

haskell:将偶数和奇数元素拆分为元组

  •  3
  • Matt  · 技术社区  · 16 年前

    我不能用高阶函数。我就是不知道该怎么做。我对哈斯克尔很陌生。它还必须是递归的。

    split :: [Int] -> ([Int],[Int])
    split xs = 
    

    我要从这个开始。老实说,我甚至不知道从哪里开始这个问题。

    实例:

    split []
    ([],[])
    
    split [1]
    ([1],[])
    
    split [1,2,3,4,5,6,7,8,9,10]
    ([1,3,5,7,9],[2,4,6,8,10])
    

    任何帮助都将不胜感激。

    编辑:它的偶数和奇数位置。

    所以

    拆分[3,6,8,9,10]将是 ([3,8,10],[6,9])

    好吧,所以我想到了这个。它不漂亮,但似乎工作正常。

    split :: [Int] -> ([Int],[Int])
    split [] = ([],[])
    split [xs] = ([xs],[])
    split xs = (oddlist xs, evenlist xs)
    
    oddlist :: [Int] -> ([Int])
    oddlist xs | length xs <= 2 = [head(xs)]
               | otherwise = [head(xs)] ++ oddlist(tail(tail(xs)))
    
    evenlist :: [Int] -> ([Int])
    evenlist xs | length xs <= 3 = [head(tail(xs))]
                | otherwise = [head(tail(xs))] ++ evenlist(tail(tail(xs)))
    
    5 回复  |  直到 10 年前
        1
  •  17
  •   kennytm    16 年前
    split [] = ([], [])
    split [x] = ([x], [])
    split (x:y:xs) = (x:xp, y:yp) where (xp, yp) = split xs
    
        2
  •  5
  •   dfeuer    10 年前

    split :: [a] -> ([a],[a])
    split = foldr (\x ~(y2,y1) -> (x:y1, y2)) ([],[])
    

    ~ split

    foldr

    split :: [a] -> ([a],[a])
    split [] = ([],[])
    split (x : xs) = (x : y1, y2)
      where
        (y2, y1) = split xs
    
        3
  •  3
  •   Tom Lokhorst    16 年前

    -- Base case:
    split [] = …
    
    -- Recurrence:
    split (x : xs) = (do something with x) … (split xs) …
    
        4
  •  2
  •   Matt Ellen Bipin Vayalu    16 年前

    split xs = (everyother 0 xs, everyother 1 xs)
          where everyother _ []     = []
                everyother 1 (x:xs) = everyother 0 xs
                everyother 0 (x:xs) = x : (everyother 1 xs)
    

        5
  •  1
  •   Community Mohan Dere    9 年前

    Get every Nth element

    ghci> let split ys = let skip xs = case xs of { [] -> [] ; [x] -> [x] ; (x:_:xs') -> x : skip xs' } in (skip ys, skip . drop 1 $ ys)
    ghci> split [1..10]
    ([1,3,5,7,9],[2,4,6,8,10])
    

    split xs = (skip xs, skip . drop 1 $ xs)
      where 
      skip [] = []
      skip [x] = [x]
      skip (x:_:xs') = x : skip xs'
    
    推荐文章