【发布时间】:2012-04-06 04:52:38
【问题描述】:
以下两个函数极其相似。它们从 [String] n 个元素中读取,[Int] 或 [Float]。我怎样才能把通用代码分解出来?我不知道 Haskell 中有任何机制支持将类型作为参数传递。
readInts n stream = foldl next ([], stream) [1..n]
where
next (lst, x:xs) _ = (lst ++ [v], xs)
where
v = read x :: Int
readFloats n stream = foldl next ([], stream) [1..n]
where
next (lst, x:xs) _ = (lst ++ [v], xs)
where
v = read x :: Float
我是 Haskell 的初学者,所以欢迎我的代码中的任何 cmets。
【问题讨论】:
-
这里不用折,用一张简单的图就能搞定。例如
map read stream :: [Int]此外,您可能想了解为什么要在 Haskell 中使用 foldr 而不是 foldl。 -
@EdwardKmett 感谢您的建议。我真正想要的是只读取前 n 个元素,并返回列表和流的其余部分。我昨天超级困,想不通。我想您想说的是,使用 foldr 我可以直接使用构造函数:对吗?我后来改写成
(map read firstn, rest) where (firstn, rest) = splitAt n stream,和你建议的很相似。 -
你不需要嵌套
where;您可以将next (lst, x:xs) _ = ...和v = ...放在连续的行中。