gpt4 book ai didi

haskell - 在 Haskell 中定义一个函数,如果它是由 'a' 组成的列表,则返回 true,否则返回 false

转载 作者:行者123 更新时间:2023-12-02 10:12:10 24 4
gpt4 key购买 nike

我是 Haskell 新手,我正在尝试编写一个接受列表并返回 bool 的函数。

如果输入列表是仅由'a'组成的列表,则返回True,否则返回False

这是我最好的猜测:

f :: [a] -> Bool

f ('a':[]) = True

f (x:xs) = False

编译失败并返回:

Couldn't match type `a' with `Char'
`a' is a rigid type variable bound by
the type signature for f :: [a] -> Bool at charf.hs:6:1
In the pattern: 'b'
In the pattern: 'b' : []
In an equation for `f': f ('b' : []) = True

我的逻辑有什么错误?

最佳答案

f :: [Char] -> Bool
f ['a'] = True
f _ = False

使用模式匹配。您的函数似乎无法处理空列表。此外,您的函数不能像您想要的那样通用,因为它显然需要一个 [Char] (或 String)。

关于haskell - 在 Haskell 中定义一个函数,如果它是由 'a' 组成的列表,则返回 true,否则返回 false,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18164772/

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