【问题标题】:How to use map in Haskell with a variable and a list如何在 Haskell 中使用带有变量和列表的地图
【发布时间】:2019-10-30 03:21:06
【问题描述】:

我打算写一个 map 函数,它本质上接受一个变量和一个列表并返回一个列表。

我尝试使用标准地图,但从我所看到的格式“地图函数列表”中,当我在这里尝试传递另一个参数时,这是另一个点。

data Point = {xCoord :: Int,
              yCoord :: Int}

movePoint :: Point -> Point -> Point
movePoint (Point x y) (Point xMove yMove)
    = Point (x + xMove)  (y + yMove)

 // Add a "vector" to a list of points
movePoints :: [Point] -> Point -> [Point]
movePoints = error "Not yet"

例如,如果我有一个向量,例如 (2,2),并且我有一个点列表,例如 [(-2,1),(0,0), (5,4) 等] 我想使用 map 将 (2,2) 添加到列表中的所有点并返回点列表,我不知道该怎么做。我是 Haskell 的新手,所以任何提示都会很棒。

【问题讨论】:

  • 只是评论而不是回答您的问题:您提到将向量添加到点(这是有道理的),然后编写了一个将点添加到点的 movePoint 函数。我知道 Vector 和 Point 都是 Ints 对,但最好为 Vector 定义不同的数据类型,然后编写 movePoint :: Point -> Vector -> Point。
  • 这可能只是一个错字,但您的数据声明需要一个构造函数。所以data Point = Point {xCoord :: Int, yCoord :: Int}

标签: list haskell functional-programming map-function arity


【解决方案1】:

部分应用 movePoint 函数(即,使用比它需要的更少的参数调用它),如下所示:

movePoints pts vec = map (movePoint vec) pts

这样做会创建一个只需要一个参数的新函数,即您第一次没有提供的那个。这称为柯里化。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2010-12-02
    • 2017-05-16
    • 2016-04-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-12-04
    相关资源
    最近更新 更多