Haskell,如何检查palindrom

Fas*_*ger 3 haskell function

我有一个小问题.True即使角色是大写字母,我怎么能扩展我的功能才能返回.

我的函数适用于列表中的字符串:

f1 w = w == reverse w

Test:
*Main> let test = ["Boob"]
*Main> f1 test
True

*Main> let test2 = "Boob"
*Main> f1 test2
False
Run Code Online (Sandbox Code Playgroud)

问候,

马丁

eps*_*lbe 6

关于什么

import Data.Char (toLower)

f1 :: String -> Bool
f1 w = w == reverse w

f2 :: String -> Bool
f2 str = f1 $ map toLower str
Run Code Online (Sandbox Code Playgroud)

但我建议的是为你的功能使用好名字

testPalindrome = f1
ignoreCase = map toLower
Run Code Online (Sandbox Code Playgroud)

然后

testPalindrome' = testPalindrome . ignoreCase
Run Code Online (Sandbox Code Playgroud)

更新:

.是功能的连接:

(.) :: (b -> c) -> (a -> b) -> (a -> c)
(g . f) x = g (f x)


     f
 A -----> B
  \       |
   \      |
g.f \     |g
     \    |
      V   V
        C
Run Code Online (Sandbox Code Playgroud)

UPDATE2

@dfeuer在评论中提到了一个非常优雅的解决方案

import Data.Function (on)
import Data.Char (toLower)

(=~=) :: String -> String -> Bool
-- | Equivalence of Strings, by ignoring the case
(=~=) = (==) `on` toLower

testPalindrome :: String -> Bool
testPalindrome w = w =~= reverse w
Run Code Online (Sandbox Code Playgroud)

该函数on(使用带有反引号语法的中缀)接受一个函数(==)和一个"修饰符函数" toLower并将其应用于该函数的参数.

(f `on` g) x y = f (g x) (g y)
Run Code Online (Sandbox Code Playgroud)

这对二进制运算符特别有用,例如(==),(<)等等.