gpt4 book ai didi

haskell - 如何在 GHCi 中使用多个 where 子句?

转载 作者:行者123 更新时间:2023-12-03 12:33:51 26 4
gpt4 key购买 nike

我第一次玩 GHCi,我在编写多行函数时遇到了一些麻烦。
我的代码如下:

Prelude> :{
Prelude| let diffSquares lst = abs $ squareOfSums lst - sumOfSquares lst
Prelude| where
Prelude| squareOfSums lst = (fst (sumsAndSquares lst))^2
Prelude| sumOfSquares lst = snd (sumsAndSquares lst)
Prelude| sumsAndSquares = foldl (\(sms,sqrs) x -> (sms+x,sqrs+x^2)) (0,0)
Prelude| :}

它给出了以下错误:
<interactive>:1:142: parse error on input `='

有人可以指出我所缺少的方向吗?

最佳答案

来自 ghci 的帮助手册( http://www.haskell.org/ghc/docs/6.10.4/html/users_guide/interactive-evaluation.html ):

Such multiline commands can be used with any GHCi command, and the lines between :{ and :} are simply merged into a single line for interpretation. That implies that each such group must form a single valid command when merged, and that no layout rule is used.



因此,您必须在每个定义之间插入分号,例如
Prelude> :{
Prelude| let a x = g
Prelude| where
Prelude| g = p x x; {- # <----- # -}
Prelude| p a b = a + b
Prelude| :}

编辑:在最新版本的 GHCi 中,您似乎需要一对大括号。
Prelude> :{
Prelude| let { a x = g
Prelude| where
Prelude| g = p x x
Prelude| p a b = a + b
Prelude| }
Prelude| :}
Prelude> a 5
10

关于haskell - 如何在 GHCi 中使用多个 where 子句?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3067885/

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