gpt4 book ai didi

Haskell As 模式,将变量绑定(bind)到常量

转载 作者:行者123 更新时间:2023-12-01 11:12:09 26 4
gpt4 key购买 nike

(这段代码没有多大意义,但我需要这个逻辑才能在我的其他复杂函数中工作):

import Data.List

elemIndex1 xss@(x:xs) =
if (x == ' ')
then (elemIndex x xss)
else (elemIndex1 xs)

所以我希望这个函数给出这个:

elemIndex1 "qwe asd zxc"
Just 3

相反,它给出了这个:

elemIndex1 "qwe asd zxc"
Just 0

据我了解,在 else 子句中 xss 实际上变成了 xs。所以我的问题是:是否有可能将变量 (x:xs) 绑定(bind)到一个常量并在任何迭代中使用这个常量?

最佳答案

您似乎期望 xss@(x:xs) 如下所示:

  • xss:给 elemIndex1 的原始字符串
    • x:任意调用的第一个字符
    • xs:任意调用的剩余字符

例如对于您的示例,当 x 首次匹配空格时

xss = "qwe asd zxc"
x = ' '
xs = "asd zxe"

这不是模式匹配的工作方式。 xss 实际上等于 x:xs,因此在该示例中它将是 "asd zxc"

如果您想保留对函数的第一次调用,可以使用在原始函数范围内调用的辅助函数。

weirdElemIndex str = weirdElemIndex' str
where
weirdElemIndex' "" = Nothing
weirdElemIndex' (x:xs) =
if x == ' '
then elemIndex ' ' str
else weirdElemIndex' xs

请注意,我在辅助函数主体中引用的 str 在其调用中将是常量。

就其值(value)而言,您设计的示例似乎等同于 elemIndex ' ',因为它通过返回 Nothing 来处理字符串中没有空格的情况.

关于Haskell As 模式,将变量绑定(bind)到常量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58791756/

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