虽然unfoldr
大概是什么意思任务,你可以,如果你使用foldr
作为hylomorphism,那就是建立一个列表,而它的另一个泪写这使用foldr
下。
digits :: Int -> [Int]
digits n = snd $ foldr go (n, []) places where
places = replicate num_digits()
num_digits | n > 0 = 1 + floor (logBase 10 $ fromIntegral n)
| otherwise = 0
go() (n, ds) = let (q,r) = n `quotRem` 10 in (q, r : ds)
实际上,我们在这里所做的是使用foldr
“地图,用状态”。我们知道提前 需要输出多少位数(使用log10)而不是那些数字是什么,所以我们使用 单位(()
)值作为这些数字的替代值。
如果你的老师只是有foldr
在顶层一个坚持己见的人,你可以得到 逃脱使go
部分:
digits' :: Int -> [Int]
digits' n = foldr go [n] places where
places = replicate num_digits()
num_digits | n > 0 = floor (logBase 10 $ fromIntegral n)
| otherwise = 0
go() (n:ds) = let (q,r) = n `quotRem` 10 in (q:r:ds)
这对非正数稍有不同的行为:
>>> digits 1234567890
[1,2,3,4,5,6,7,8,9,0]
>>> digits' 1234567890
[1,2,3,4,5,6,7,8,9,0]
>>> digits 0
[]
>>> digits' 0
[0]
>>> digits (negate 1234567890)
[]
>>> digits' (negate 1234567890)
[-1234567890]
你确定你不能使用'unfoldr'吗?还是别的什么?所有的折叠功能需要一些列表(或“折叠”)作为输入折叠... – Alec
亚历克,我不熟悉展开*。我认为可能,这是要走的路(以及问题要求的实际含义)。谢谢。 –
你可以用'list_digits = unfoldr(\ i - > if if == 0 then Nothing else let(q,r)= quotRem i 10在Just(r,q))''中很容易地获得数字。 – Alec