在一個函式中,我應該對串列的元素進行編號,它應該像這樣回傳:“n:字串的其余部分”
numberLines :: [String] -> [String]
["asd qwe", "-- Foo", "", "\thello world "]
-> ["1: asd qwe", "2: -- Foo", "3: ", "4: \thello world "]
我不允許使用簡單的遞回,只能使用高階函式(如果需要)
我的問題:
- 我不知道如何制作柜臺
- 我不知道如何將 Int 放在字串前面(
"counter: " "string"不起作用)
uj5u.com熱心網友回復:
您可以使用zipWith :: (a -> b -> c) -> [a] -> [b] -> [c]它同時列舉兩個串列并生成一個專案串列,其中c i是fa i b i for 。例如,作為第一項,您可以為它提供一個無限串列,作為第二項,您可以為它提供行串列,因此:c = zipWith f a b[1..]
numberLines :: [String] -> [String]
numberLines = zipWith f [1..]
where f idx st = …
您仍然需要填寫的…部分。
uj5u.com熱心網友回復:
很多人希望你使用zipWith. 雖然這會給出正確的答案,但它會消耗兩個串列,因此不完全支持串列融合,一次只能處理一個串列。這是一個可以完全融合的替代解決方案:
numberLines :: [String] -> [String]
numberLines xs = foldr (\st acc idx -> …:acc (idx 1)) mempty xs 1
正如 Willem Van Onsem 的回答一樣,您需要自己填寫該…部分。
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/536674.html
標籤:哈斯克尔
