这可能是一个非常愚蠢的问题,但..
我编写了两个快速函数来检查三个数字是按降序还是按升序排列.
IE 2 3 5对于升序是正确的而对于降序是错误的.
1 5 3对于两者都是错误的
我需要制作第三个函数,只需调用前两个函数即可.我正在使用GHCi.第三个函数查看数字是否与上面第二个例子中的任何顺序不同
所以它会是这样的
let newfunction = (not)Ascending && (not)Descending
Run Code Online (Sandbox Code Playgroud)
我怎么做呢?/ =对我不起作用
ert*_*tes 29
实际上有一个not
布尔函数,但一如既往,你必须得到正确的类型.假设您现有的函数具有以下类型:
ascending :: (Ord a) => [a] -> Bool
ascending (x1:x2:xs) = x1 <= x2 && ascending (x2:xs)
ascending _ = True
descending :: (Ord a) => [a] -> Bool
descending (x1:x2:xs) = x1 >= x2 && descending (x2:xs)
descending _ = True
Run Code Online (Sandbox Code Playgroud)
要求两者都意味着列表必须相同,因为这是他们在上面定义的意义上升序和降序的唯一方法:
both xs = ascending xs && descending xs
Run Code Online (Sandbox Code Playgroud)
要反转布尔值,有以下not
功能:
not :: Bool -> Bool
Run Code Online (Sandbox Code Playgroud)
然后这两个函数都没有表达:
neither xs = not (ascending xs || descending xs)
Run Code Online (Sandbox Code Playgroud)
当然,这与:
neither xs = not (ascending xs) && not (descending xs)
Run Code Online (Sandbox Code Playgroud)
你可以使用阅读器仿函数的应用风格,使这看起来更令人愉快:
import Control.Applicative
both = liftA2 (&&) ascending descending
neither = not . liftA2 (||) ascending descending
Run Code Online (Sandbox Code Playgroud)
或者:
neither = liftA2 (&&) (not . ascending) (not . descending)
Run Code Online (Sandbox Code Playgroud)
更多:这产生了谓词的概念:
type Predicate a = a -> Bool
Run Code Online (Sandbox Code Playgroud)
谓词是布尔函数.两个功能ascending
和descending
上面所定义是谓词.相反,反转布尔值,你可以反转谓词:
notP :: Predicate a -> Predicate a
notP = (not .)
Run Code Online (Sandbox Code Playgroud)
而不是对布尔值进行连接和分离,我们可以将它们放在谓词上,这样可以更好地编写复合谓词:
(^&^) :: Predicate a -> Predicate a -> Predicate a
(^&^) = liftA2 (&&)
(^|^) :: Predicate a -> Predicate a -> Predicate a
(^|^) = liftA2 (||)
Run Code Online (Sandbox Code Playgroud)
这让我们写both
和neither
真的很好:
both = ascending ^&^ descending
neither = notP ascending ^&^ notP descending
Run Code Online (Sandbox Code Playgroud)
以下法则适用于谓词,
notP a ^&^ notP b = notP (a ^|^ b)
Run Code Online (Sandbox Code Playgroud)
所以我们可以neither
更好地重写:
neither = notP (ascending ^|^ descending)
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
19787 次 |
最近记录: |