我正在阅读“制作我们自己的类型和类型类”的部分内容,其中部分内容来自“向您学习 Haskell 的伟大之处!”。
按照文本,我在 GHCi 中编写了代码并出现错误。
data Shape = Circle Float Float Float | Rectangle Float Float Float Float
surface :: Shape -> Float
<interactive>:2:1: error:
Variable not in scope: surface :: Shape -> Float
Run Code Online (Sandbox Code Playgroud)
当我通过文本编辑器编写代码并从 GHCi 加载时,它可以正常工作。
我应该如何在 GHCi 中定义数据类型?
您正确定义了数据类型,但是当您想在 GHCi 中输入多行语句时,您需要使用:{和:},或者使用其他机制来制作多行语句。因此,您可以输入:
Prelude> data Shape = Circle Float Float Float | Rectangle Float Float Float Float
Prelude> :{
Prelude| surface :: Shape -> Float
Prelude| surface (Circle _ _ r) = pi * r ^ 2
Prelude| surface (Rectangle x1 y1 x2 y2) = (abs $ x2 - x1) * (abs $ y2 - y1)
Prelude| :}Run Code Online (Sandbox Code Playgroud)