在 haskell 中使用 lambda 函数应用程序?

function application with lambda in haskell?

正在测试此代码:

-- | this function checks if string or list are a palindrome
    isPalindrome :: (Eq a) => [a] -> Bool
    isPalindrome x =
        if reverse x == x
            then True
            else False

我设法写了这个:

-- | how do I remove ugly parentheses our of here?
palindromeTest verb = isPalindrome ((\verb -> verb ++ reverse verb) verb )  == True
    where types = verb::String

括号看起来很恶心,我该如何解决?

palindromeTest

你的表情:

(\verb -> verb ++ reverse verb) verb

没有多大意义:等效的表达式是:

(\x -> x ++ reverse x) verb

因为 lambda 表达式中的 verb 是局部范围的。但是您知道 x 是什么:它是 verb。因此,您可以将表达式替换为:

verb ++ reverse verb

或完整:

palindromeTest verb = isPalindrome <b>(verb ++ reverse verb)</b> == True

我们也可以去掉 == True,因为 \x -> x == True 等价于 id:

palindromeTest verb = isPalindrome (verb ++ reverse verb)

最后 where types = verb::String 也没有用:Haskell 是静态类型,类型在编译时解析。所以这个声明并没有增加任何东西。您可以在函数的类型签名中限制动词的类型:

<b>palindromeTest :: String -> Bool</b>
palindromeTest verb = isPalindrome (verb ++ reverse verb)

isPalindrome

就像palindromTest写[=18=是没用的],没理由写= True= False如果这是根据条件:只是 return 条件本身:

-- | this function checks if string or list are a palindrome
isPalindrome :: (Eq a) => [a] -> Bool
isPalindrome x = <b>reverse x == x</b>

您可以使用 ap:

使其更紧凑
<b>import Control.Monad(ap)</b>

-- | this function checks if string or list are a palindrome
isPalindrome :: (Eq a) => [a] -> Bool
isPalindrome = <b>ap (==) reverse</b>