我是 Haskell 的新手,大家可以幫我如何生成從 1 到 10 的串列。
我試著做這樣的:
seqList :: Integer -> [Integer]
seqList 1 = [1]
seqList n = n : seqList(n-1)
結果是 10 比 1,而不是 1 比 10
第二個問題,我們能否將功能作為價值。
numList :: [Integer]
numList = [1,2..10]
totJum :: Int
totJum = length numList
takeNum :: Int->[Integer]
takeNum totJum
| totJum >= 10 = take 5 numList
| totJum == 10 = numList
使用此代碼,如果 numlist 的長度與條件匹配,我想呼叫輸出。
uj5u.com熱心網友回復:
對于第一個,您可以使用accumulator:一個用于產生值的變數,并且在遞回呼叫中每次遞增,因此:
seqList :: Integer -> [Integer]
seqList n = go 1
where go i
| i <= … = …
| otherwise = …
我把這些…部分作為練習留下來。
使用此代碼,如果 numlist 的長度與條件匹配,我想呼叫輸出。
您不應將totJum其用作引數,而應僅在函式體中使用它,因此:
takeNum :: [Integer]
takeNum
| totJum >= 10 = take 5 numList
| totJum == 10 = numList
但是請注意,這里不包括totJum小于或 10 的情況。在這種情況下,函式將因此出錯。因此,您可能想要添加一個otherwise子句。
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/487898.html
上一篇:除法上的函子應用
