[英]Calling a test case in Haskell and else if statements
好的,所以我看了很多類似的問題,但我仍然有些困惑。
因此,我有使用斷言設置的多個測試用例,並且我試圖編寫一個使用測試用例的輸入以及使用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
]
對我來說,尚不清楚您要使用以下三個功能中的哪一個,所以我已經全部完成了:
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
呢? 好吧,在[fa | f <- xs]
[fa | 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]
與[fa| a <- [(>4), (==7), (<10)]]
[fa| a <- [(>4), (==7), (<10)]]
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.