-- split homework 4/5
split :: [Int] -> ([Int],[Int])
split [] = ([],[])
split [x] | (x `mod` 2 == 1) = ([x],[])
| otherwise = ([], [x])
split x = (oddlist x, evenlist x)
oddlist :: [Int] -> ([Int])
oddlist [] = []
oddlist (x : xs) | (x `mod` 2 == 1) = x : oddlist xs
| otherwise = oddlist xs
evenlist :: [Int] -> ([Int])
evenlist []= []
evenlist (x : xs) | (x `mod` 2 == 0) = x : evenlist xs
| otherwise = evenlist xs
解释:
①、定义split函数,接受int列表,返回两个int列表。
列表为空时,返回2个空列表。
列表只有一个元素的时候,判断是否为奇数,是的话加入左边列表,否的话,加入右边列表。
列表超过2个元素的情况下,左边调用奇数列表方法oddlist ,右边调用偶数列表生成方法evenlist
②、oddlist 递归奇数列表生成方法:取头元素,判断如果为奇数,返回头元素加上 ,对后面的元素进行二次递归调用。直到列表中为空的时候,停止递归。得到奇数列表
③、evenlist ,同上
谢谢!