【问题标题】:Error while passing strings in functions in Haskell在 Haskell 中的函数中传递字符串时出错
【发布时间】:2017-07-03 03:37:14
【问题描述】:

所以我在 haskell 中尝试了以下代码,我尝试检测用户是否在字符串中输入了“否”或“否”。我也尝试用字符串替换 [[Char]] ,但它给出了编译错误。

  wantGifts :: [[Char]] -> [[Char]]
  wantGifts st = [if (x == "No" || x== "no") then "No gifts given" else "But why" | x <-  st, x == head st]

上面的代码可以编译,但是当我向它传递一个字符串时,它返回一个错误消息:

*Main> wantGifts "no I dont"

<interactive>:8:11:
    Couldn't match type ‘Char’ with ‘[Char]’
    Expected type: [[Char]]
      Actual type: [Char]
    In the first argument of ‘wantGifts’, namely ‘"no I dont"’
    In the expression: wantGifts "no I dont"
    In an equation for ‘it’: it = wantGifts "no I dont"

【问题讨论】:

  • 错误表示该函数需要一个字符串列表(list-of-lists-of-chars),但您没有传递一个。

标签: list function haskell char


【解决方案1】:

仔细查看wantGifts的类型,它需要一个字符列表列表。但是"no I dont" 的类型为String,即[Char]。根据您当前的结构,您必须使用:

wantGifts ["no I dont"]

有几种方法可以改善这一点,最好是使用Text

import Data.Text (Text)
import qualified Data.Text as T
wantGifts :: Text -> Text 
wantGifts txt = if (T.isInfixOf "no" . T.toLower) txt then "No gifts given" else "But why"

【讨论】:

    【解决方案2】:

    您已将wantGifts 定义为获取字符串列表。 [[Char]] 等价于 [String]。在 REPL 中,您传递给它一个字符串。

    如果你这样做,它会编译:

    wantGifts ["no I dont"]
    

    但是,我有一种预感,这不是你想要的。

    如果您尝试检测单词 "no" 是否在字符串中的任何位置,您可以使用 words 函数:

    containsNo :: String -> Bool
    containsNo = any (\w -> w == "no" || w == "No") . words
    

    【讨论】:

    • 谢谢,如果您能解释一下 \w 和任何部分,我将不胜感激。
    • 这是匿名函数的 lambda 语法。 Here is a good explanation.
    • @Sudhanshu LearnYouAHaskell 也是一个很好的学习资源。
    • @jkeuhlen 这是我学习haskell的主要资源,它肯定是一个很好的资源!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-10-15
    • 2017-02-27
    • 1970-01-01
    • 1970-01-01
    • 2012-03-27
    • 2015-11-04
    相关资源
    最近更新 更多