在Haskell中调用测试用例以及if语句

时间:2012-12-03 06:40:52

标签: haskell

好的,所以我看了很多类似的问题,但我仍然有点困惑。

所以我使用断言设置了多个测试用例,我正在尝试使用if-else语句和递归来编写使用测试用例输入和输出的程序。我的if语句一直出现解析错误。

不是实际代码只是我正在尝试做的一个例子

我的问题是如何设置一个程序来正确调用“测试”?

所以我的第一个测试用例tl1给出了一个整数“n”, 我想检查n是否为偶数然后乘以2如果它是奇数然后乘以3并将新值赋值给n

所以这是我试图编写的部分,以便接受类似于给出的测试用例代码的测试用例的输入。

tests :: if (mod n 2) = 0
         then tests (n * 2)
         else tests (n * 3)   

tests = 
        testlist [
                   tl1
                  ,tl2
                  ,tl3
                 ]

1 个答案:

答案 0 :(得分:1)

我不清楚你想要的这三个功能中的哪一个,所以我已经完成了所有这些功能:

testListAll :: [a -> Bool] -> a -> Bool
testListAll xs a = and $ map ($ a) xs

testListAny :: [a -> Bool] -> a -> Bool
testListAny xs a = or $ map ($ a) xs

testListList  :: [a -> Bool] -> a -> [Bool]
testListList xs a = map ($ a) xs

例如,

> testListAll [(> 5), (== 7), even] 4
False
> testListAny [(> 5), (== 7), even] 4
True
> testListAll [(> 5), (== 8), even] 8
True
> testListList [(> 5), (== 8), even] 10
[True,False,True]

现在我们可以编写像

这样的函数了
test :: Integral a => a -> Bool
test n = if even n 
        then testListAll [(> 5), (< 9)] n
        else testListAny [(<= 5), (> 8)] n

> test 5
True
> test 6
True
> test 7
False
> test 8
True
> test 9
True
> test 10
False
> test 11
True

说明

我将详细解释一个功能;其他人的工作非常相似。

第一个函数可能更简单地写成:

testListAll' :: [a -> Bool] -> a -> Bool
testListAll' xs a = and [f a | f <- xs]

所以它做的是从列表中取出每个测试函数f并将其应用于测试值a。如果列表中的所有内容都为True,则函数and :: [Bool] -> Bool给出True;此函数检查是否满足所有检查。

那我为什么要把右手写为and $ map ($ a) xs?好吧,在[f a | f <- xs]我对f的所有元素xs做了同样的事情,所以我立刻想到用map做这件事。

首先考虑一下

  map (+ 4) [1,2,3,4]
= [(+4) 1,  (+4) 2,  (+4) 3, (+4) 4]
= [1+4, 2+4, 3+4, 4+4]
= [5,6,7,8]

了解我们如何使用(低优先级)函数应用程序运算符$

  map ($ a) [(>4), (==7), (<10)]
= [($ a) (>4),  ($ a) (==7),  ($ a) (<10)]
= [(>4) $ a,  (==7) $ a,  (<10) $ a]
= [(>4) a,  (==7) a,  (<10) a]
= [a > 4 , a==7, a < 10]

其结果与[f a| a <- [(>4), (==7), (<10)]]相同。