-6ren">
gpt4 book ai didi

haskell - 如何在列表理解中使用字符串而不是 char

转载 作者:行者123 更新时间:2023-12-05 09:02:52 25 4
gpt4 key购买 nike

现在我正在尝试创建一个函数来查看输入是否为 item已经在list ,这是我的代码。

list :: [String]
list = ["a","b"]

listCheck :: String -> [String]
listCheck item = [(x:xs)| (x:xs) <- list, x == item]

当前的问题是它只能在输入是字符而不是字符串时进行过滤,当我留下未声明的类型时 Haskell 使函数 Char -> [String] ,并且它工作得非常好,当它不被包含时它返回一个空列表,如果它被包含它返回一个包含该项目的列表。当我添加 String -> [String]它返回了这个错误。

Couldn't match type `[Char]' with `Char'
Expected: Char
Actual: String

我尝试将其更改为 x <- item它编译了但它只给出了[item, item]每次。我想知道我可以做些什么来让它使用字符串而不是字符,谢谢。

最佳答案

这部分将 x 转换为 char。

(x:xs) <- list

每个元素的映射关系

["a","b"]

'a':[] => x = 'a', xs = []
'b':[] => x = 'b', xs = []

所以,如果你想检查列表中的元素并找到一个,下面怎么样。

listCheck :: String -> [String]
listCheck item = [x| x <- list, x == item]
Prelude> listCheck "a"
["a"]
Prelude> listCheck "b"
["b"]
Prelude> listCheck "c"
[]
Prelude>

关于haskell - 如何在列表理解中使用字符串而不是 char,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/70704354/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com