Haskell: split even and odd elements into a tuple

I cannot use high order functions. I just can't figure out how to do this. I am very new to haskell. It must also be recursive.

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

It is given to me to begin with. I honestly don’t even know where to start this problem.

Examples:

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])

any help would be greatly appreciated.

Edit: even and odd positions.

So,

the split [3,6,8,9,10] will be ([3,8,10], [6,9])

OK, so I came up with this. This is not very, but it seems that everything is fine.

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)))
+3
source share
5 answers
split [] = ([], [])
split [x] = ([x], [])
split (x:y:xs) = (x:xp, y:yp) where (xp, yp) = split xs
+16
source

If you are not allowed to use higher-order list functions, your alternative is mainly to use recursion.

, :

-- Base case:
split [] = …

-- Recurrence:
split (x : xs) = (do something with x) … (split xs) …
+3

, :

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)

, - 0.

+2

" ", :

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
+2

, N- .

, , :

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'
+1
source

Source: https://habr.com/ru/post/1764648/


All Articles