【问题标题】:How can I apply to functions to a list in haskell?如何将函数应用于 haskell 中的列表?
【发布时间】:2021-08-01 09:41:42
【问题描述】:

我正在尝试编写一个函数来检查给定列表是否是回文。但是,我不知道如何将函数应用于给定的输入。 我的代码如下所示:

isPalindrome :: [a] -> Bool
isPalindrome x
  | head x == last x = True
  | otherwise = isPalindrome tail (init x)

这不起作用,我不知道为什么。

【问题讨论】:

  • 在语法上,您的意思是isPalindrome (tail (init x)),带有额外的一对括号。

标签: list haskell palindrome


【解决方案1】:

代码的主要问题是逻辑 - 它是说“如果头部和尾部匹配,则它是回文,则接受。否则......”真正的测试是“如果头部和尾部不同,则拒绝。否则检查中心部分。”

【讨论】:

    【解决方案2】:

    你必须在案例中思考,这个函数可以解决问题:

    isPalindrome []       = True   
    isPalindrome [x]      = True   
    isPalindrome [x,y]    = x == y 
    isPalindrome xs       = (head xs) == (last xs) && isPalindrome ((tail . init) xs)
    

    举个例子:

    isPalindrome "aabaa"  -->
    isPalindrome "aabaa"   = (head "aabaa") == (last "aabaa") && isPalindrome ((tail . init) "aabaa")
    

    下一步)

    isPalindrome "aabaa"  = ('a') == ('a') && isPalindrome "aba"
    

    下一步)isPalindrome "aba"

    (head "aba") == (last "aba") && isPalindrome ((tail . init) "aba")
    

    下一步->

    ('a') == ('a') && isPalindrome "b")
    

    最后一步 ->

    isPalindrome "b"
    isPalindrome [x]      = True 
    

    所以我们有表达式:

     ('a') == ('a') && ('a') == ('a') && True --> True
    

    【讨论】:

    • 谢谢,但这似乎仍然不起作用。当我试用你的代码时,我得到了编译器错误:``` 99probs.hs:27:27: error: * No instance for (Eq a) 由于使用 ==' Possible fix: add (Eq a) to the context of the type signature for: isPalindrome :: forall a. [a] -> Bool * In the expression: x == y In an equation for isPalindrome': isPalindrome [x, y ] = x == y 27 | isPalindrome [x,y] = x == y ´´´ 你能解释一下,为什么会这样吗?我需要添加一个 EQ 类型类吗?
    • 只是不要将类型添加到方程中,Haskell 会为您推断它
    • 我的意思是不要添加这种类型isPalindrome :: [a] -> Bool让haskell为你推断它,尽量不要添加该行,它会编译
    猜你喜欢
    • 2020-03-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-06-29
    • 1970-01-01
    • 2021-12-08
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多