我正在尝试使用以下代码编写一个 Haskell 模块:
module RectangleMover where
data Rectangle = Rectangle { xCoordinate :: Int
, yCoordinate :: Int
, width :: Int
, height :: Int
} deriving (Show)
move :: Rectangle -> Int -> Int -> Rectangle
-- Edit 1
move rec x y =
let rec' = { xCoordinate + x
, yCoordinate + y
}
return rec
要创建一个矩形,我会输入:
let rec = Rectangle 10 10 20 30
但我现在的问题是如何实现一个“移动”这个矩形的函数?
在 C# 或 Java 中,调用是这样的:
rec.move(20,20);
但是这将如何用 Haskell 编写呢?不幸的是,这是我第一次尝试使用函数式编程语言......
编辑 1:
我在函数中添加了代码,但在“xCoordinate + x”处仍然出现解析错误......
最佳答案
鉴于这是您第一次使用 Haskell,请使用已经提到的记录更新答案。但是,对于将来在谷歌上搜索的人,以及如果你感觉更有野心(或为了 future 的学习)的你,Haskell 有这个非常受欢迎且非常强大的库,称为 lens。 .
以下是如何使用它来设计解决问题的方法。
{-# LANGUAGE TemplateHaskell #-}
import Control.Lens
data Rectangle = Rectangle { _xCoordinate :: Int
, _yCoordinate :: Int
, _width :: Int
, _height :: Int
} deriving (Show)
makeLenses ''Rectangle
move :: Rectangle -> Int -> Int -> Rectangle
move rect dx dy= rect
& xCoordinate +~ dx
& yCoordinate +~ dy
这个解决方案一开始可能看起来并不更强大,但是当您开始尝试更新嵌套记录时,我向您保证优势变得明显。
关于haskell - 在 Haskell 中更改记录值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38085955/