gpt4 book ai didi

Haskell 嵌套 where 子句和 "let ... in"语法

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

我刚开始使用 Haskell。

这个嵌套的 where 子句有什么问题?

length' a = fromIntegral (length a)

isPalin1 xs = fstHalf == reverse sndHalf
where
fstHalf = take halfLength xs
sndHalf = drop halfLength xs
where halfLength = (length' xs) / 2

我得到的错误: isPalin1.hs:5:32: Not in scope: ‘halfLength’
以下也是错误的,希望有人能告诉我为什么:

length' a = fromIntegral (length a)

isPalin2 xs = fstHalf == reverse sndHalf
where
let
halfLength = (length' xs) / 2
in
fstHalf = take halfLength xs
sndHalf = drop halfLength xs

错误信息:
isPalin2.hs:7:17:
parse error (possibly incorrect indentation or mismatched brackets)

最佳答案

where只适用于一个绑定(bind),所以 halfLength在您的第一个片段中仅对 sndHalf 可用.你应该这样写:

length' a = fromIntegral (length a)

isPalin1 xs = fstHalf == reverse sndHalf
where
halfLength = (length' xs) / 2
fstHalf = take halfLength xs
sndHalf = drop halfLength xs

这是因为 where本身就是一个作用域,所以绑定(bind)可以相互引用。

至于你的第二个片段,那是完全不正确的。一个 let ⋯ in statement 严格来说是一个表达式,不能在 where 的绑定(bind)上下文中使用。 .

如果你在哪里使用 let ⋯ in ,你会像这样使用它:
length' a = fromIntegral (length a)

isPalin1 xs =
let halfLength = (length' xs) / 2
fstHalf = take halfLength xs
sndHalf = drop halfLength xs
in fstHalf == reverse sndHalf

关于Haskell 嵌套 where 子句和 "let ... in"语法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29575128/

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