gpt4 book ai didi

haskell - 简化haskell函数

转载 作者:行者123 更新时间:2023-12-02 08:21:01 24 4
gpt4 key购买 nike

我真的很难使用 Haskell atm。

我花了将近 6 个小时来编写一个可以完成我想要的功能的函数。不幸的是我对它的外观不满意。

有人可以给我一些如何重写它的提示吗?

get_connected_area :: Eq generic_type => [[generic_type]] -> (Int, Int) -> [(Int,Int)] -> generic_type -> [(Int,Int)]
get_connected_area habitat point area nullValue
| elem point area = area
| not ((fst point) >= 0) = area
| not ((snd point) >= 0) = area
| not ((fst point) < (length habitat)) = area
| not ((snd point) < (length (habitat!!0))) = area
| (((habitat!!(fst point))!!(snd point))) == nullValue = area
| otherwise =
let new_area = point : area
in
get_connected_area habitat (fst point+1, snd point) (
get_connected_area habitat (fst point-1, snd point) (
get_connected_area habitat (fst point, snd point+1) (
get_connected_area habitat (fst point, snd point-1) new_area nullValue
) nullValue
) nullValue
) nullValue

函数 get 是一个 [[generic_type]](表示景观 map ),并搜索不等于给定 nullValue 的点周围的完全连接区域。

例如:

如果函数像这样被调用:

get_connected_area [[0,1,0],[1,1,1],[0,1,0],[1,0,0]] (1,1) [] 0

字面意思就是

0 1 0
1 1 1
0 1 0
1 0 0

代表 map (如谷歌地图)。从点(坐标)(1,1)开始我想获取与给定点形成连通区域的元素的所有坐标。

因此结果应该是:

0 1 0
1 1 1
0 1 0
1 0 0

以及对应的返回值(粗体1的坐标列表):

[(2,1),(0,1),(1,2),(1,0),(1,1)]

最佳答案

一个小变化是您可以对变量 point 使用模式匹配。这意味着您可以使用 (x, y)而不是point在函数声明中:

get_connected_area habitat (x, y) area nullValue = ...

现在随处可见fst point ,只需输入 x ,以及您所在的任何地方 snd point ,输入y .

另一个修改是为子表达式使用更多变量。这可以帮助嵌套递归调用。例如,为最内部的嵌套调用创建一个变量:

....
where foo = get_connected_area habitat (x, y-1) new_area nullValue

现在只需输入 foo而不是打电话。现在可以对“新的”最内部调用重复此技术。 (请注意,您应该选择一个比 foo 更具描述性的名称。也许 down ?)

请注意not (x >= y)x < y 相同。使用它来简化所有条件。由于这些条件测试一个点是否在边界矩形内,因此大部分逻辑可以分解为函数 isIn :: (Int, Int) -> (Int, Int) -> (Int, Int) -> Bool这将使 get_connected_area更具可读性。

关于haskell - 简化haskell函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46025613/

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