我必須根據這個簽名定義一個函式:
indexList :: [a] -> [(Int, a)]
該函式應該將串列元素解壓縮到一個元組中 - 元組的第一部分是元組距離串列末尾的距離 - 第二部分是原始元素本身。(必須是遞回的,我不能使用length函式)。
期望這個測驗是真的:
indexList [True, False, True] == [(2, True), (1, False), (0, True)]
到目前為止,我已經到了這里:
indexList [] = []
indexList (x : xs) = ({-HowFarIsIt-}, x) : indexList xs
uj5u.com熱心網友回復:
您可以查看結果的下一個元組的結果,因此:
indexList :: [a] -> [(Int, a)]
indexList [] = []
indexList [x] = [(0, x)]
indexList (x : xs) = … : ys
where ys@((i,_):_) = indexList xs
我把填寫…作為練習留在那里。
您還可以使用輔助函式來啟用完全模式匹配:
import Data.List.NonEmpty(NonEmpty((:|)), (<|))
indexList :: [a] -> [(Int, a)]
indexList [] = []
indexList (x : xs) = let (x :| xs) = indexList' x xs in x : xs
indexList' :: a -> [a] -> NonEmpty [(a, Int)]
indexList' x [] = (0, x) :| []
indexList' x xs = … <| ys
where ys@((i,_) :| _) = indexList' x xs
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/517136.html
標籤:列表哈斯克尔函数式编程
上一篇:Haskell:掃描一個陣列
