我正在使用 Haskell 实现的生成器来完成家庭作业。我有一个andAlso
函数应该为生成器添加一个额外的谓词,但它在所有测试用例中都无法正常工作。虽然它看起来是正确的
这是我的生成器类型定义:
-- Type definition for a generator: a function producing a sequence of values
-- 1. The first function generates the next value.
-- 2. The second function checks if generation should continue.
-- 3. The third value is the initial value, or seed. It does not count as being generated by the generator.
type Generator a = (a -> a, a -> Bool, a)
我目前的实现andAlso
:
-- Adds an additional predicate to a generator.
andAlso :: (a -> Bool) -> Generator a -> Generator a
andAlso p (f, g, s) = (f, \x -> g x && p x, s)
我正在使用辅助函数takeGen
来可视化测试结果:
takeGen :: Int -> ((a -> a), (a -> Bool), a) -> [a]
takeGen 0 _ = []
takeGen n (next, pred, seed)
| not (pred seed) = []
| otherwise = seed : takeGen (n-1) (next, pred, next seed)
测试用例和结果
以下是我的测试用例及其结果:
-- Test 1: Filter for odd numbers
takeGen 10 (andAlso (\x -> x `mod` 2 == 1) ((+1), (<10), 0))
-- Expected: [1,3,5,7,9], but getting: [1]
-- Test 2: Filter for numbers divisible by 3
takeGen 10 (andAlso (\x -> x `mod` 3 == 0) ((+1), (<10), 0))
-- Expected: [0,3,6,9], but getting: [0]
-- Test 3: Filter for numbers greater than 5
takeGen 10 (andAlso (>5) ((+1), (<10), 0))
-- Works correctly: [6,7,8,9]
-- Test 4: Combine two additional predicates
takeGen 10 (andAlso (>3) (andAlso (<8) ((+1), (<10), 0)))
-- Works correctly: [4,5,6,7]
-- Test 5: Test with a different generator function
takeGen 10 (andAlso (<15) ((+2), (<20), 1))
-- Works correctly: [1,3,5,7,9,11,13]
takeGen 10 (andAlso (<10) ((+1), (<10), 0))
-- Works correctly: [0,1,2,3,4,5,6,7,8,9]
我尝试过的方法
我尝试过的各种实现andAlso
,包括:
- 当前实现如上所示
- 调整谓词在序列中的应用方式
- 尝试找到满足两个谓词的第一个有效值
一些测试用例运行正常,但其他测试用例(特别是测试 1 和 2)并未返回所有预期值。
我的问题
我的实现有什么问题andAlso
?我应该如何修复它才能使所有测试用例按预期工作?问题在于生成器的定义方式、takeGen
工作原理,还是andAlso
附加谓词的应用方式?
其他背景信息
我已经实现的其他与生成器相关的功能:
nthGen :: Integer -> Generator a -> a
nextGen :: Generator a -> Generator a
lengthGen :: Generator a -> Integer
hasLengthOfAtLeast :: Integer -> Generator a -> Bool
constGen :: a -> Generator a
foreverGen :: (a -> a) -> a -> Generator a
emptyGen :: Generator a
感谢您帮助我了解我的实施出了什么问题。