让这段代码进行测试:
-- | 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
括号看起来很恶心,我该如何解决?
答案 0 :(得分:6)
palindromeTest
你的表达:
(\verb -> verb ++ reverse verb) verb
没有多大意义:一个等价的表达式是:
(\x -> x ++ reverse x) verb
因为lambda表达式中的verb
是局部作用域。但是你知道x
是什么:它是verb
。所以你可以用以下代码替换表达式:
verb ++ reverse verb
或完整:
palindromeTest verb = isPalindrome (verb ++ reverse verb) == True
我们也可以删除== True
,因为\x -> x == True
相当于id
:
palindromeTest verb = isPalindrome (verb ++ reverse verb)
最后where types = verb::String
也没用:Haskell是静态类型的,类型在编译时被解析。所以这个陈述没有添加任何东西。您可以在函数的类型签名中限制动词的类型:
palindromeTest :: String -> Bool
palindromeTest verb = isPalindrome (verb ++ reverse verb)
isPalindrome
就像在palindromTest
中编写== True
一样没用,如果这是基于条件,则没有理由编写= True
和= False
:只需返回条件本身:
-- | this function checks if string or list are a palindrome
isPalindrome :: (Eq a) => [a] -> Bool
isPalindrome x = reverse x == x
您可以使用ap
:
import Control.Monad(ap)
-- | this function checks if string or list are a palindrome
isPalindrome :: (Eq a) => [a] -> Bool
isPalindrome = ap (==) reverse