[英]Given a list of ints a, return a new list using recursion which contains all positive elements of a
[英]Return list of tuples given a positive integer using recursion on Haskell
我正在嘗試定義一個“對”function,它給出一個正數 integer,返回一個正整數對的列表,該對的第一個分量小於或等於第二個分量,其總和等於給定正 integer。 例如:
對 7 = [(1,6),(2,5),(3,4)]
對 10 = [(1,9),(2,8),(3,7),(4,6),(5,5)]
我設法在不使用遞歸的情況下做到了這一點:
pairs :: Integral a => a -> [(a, a)]
pairs 1 = []
pairs x
| x <= 0 = error "It is not positive"
| mod x 2 == 0 = zip (enumFromTo 1 (div x 2)) (enumFromThenTo (pred x) (pred(pred x)) (div x 2))
| otherwise = zip (enumFromTo 1 (div x 2)) (enumFromThenTo (pred x) (pred(pred x)) (succ(div x 2)))
並使用遞歸:
generateTupleList:: Integral a => [(a, a)] -> [(a, a)]
generateTupleList[] = undefined
generateTupleList((a,b):[])
| (a + 1) > (b - 1) = ((a,b):[])
| otherwise = [(a,b)] ++ generateTupleList(((a+1),(b-1)):[])
pairs:: Integral a => a -> [(a, a)]
pairs 1 = []
pairs x
| x <= 0 = error "It is not positive"
| otherwise = generateTupleList[(1,x-1)]
我的問題如下,有沒有其他方法可以使用遞歸而不創建另一個子函數(在我的情況下為generateTupleList)來“配對” function?
你可以這樣做:
pairs :: Integral a => a -> [(a, a)]
pairs x = map (\y -> (y, x - y)) [1..x `div` 2]
如果您不知道, [a..b]
等效於enumFromThenTo ab
,並且將 function 包裝在反引號中使其行為類似於運算符,因此a `div` b
與div ab
相同。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.