gpt4 book ai didi

function - Haskell:if-then-else条件问题

转载 作者:行者123 更新时间:2023-12-05 01:29:23 24 4
gpt4 key购买 nike

我是 Haskell 的新手,正在尝试理解编写函数以及 if else 条件和其他所有内容。我正在尝试编写一个非常基本的函数,但我不完全理解 if-then-else 的用法。我有一个迷宫,我用 [[Char]] 表示。这个函数将简单地查看迷宫中的位置 x,y 并返回它是否是一个有效位置。 (是否在迷宫边界内)

到目前为止我已经写了这个:

is_valid_position :: Int -> Int -> [[Char]] -> Bool

is_valid_position x y maze
if(x < 0 || y < 0)
then False
if(x >= length maze || y >= length (maze!!0))
then False
else True

由于现在使用了“else”,所以会出现错误。我想用 python 写的是这样的:

def is_valid_position(maze, pos_r, pos_c):
if pos_r < 0 or pos_c < 0:
return False
if pos_r >= len(maze) or pos_c >= len(maze[0]):
return False

return True

我应该如何更改我的 Haskell 代码?感谢您的帮助。

最佳答案

if-else 表达式需要这两个部分。您可以嵌套表达式,例如 if c1 then a else if c2 then b else c

is_valid_position x y maze = if (x < 0 || y > 0)
then False
else if (x >= length maze | y >= length (maze !! 0)
then False
else True

但是,您在这里不需要 if-else 表达式,因为您纯粹是在使用 bool 值。您可以简单地使用 &&||

-- Instead of prohibiting any condition to be true,
-- require each negated condition to be true
is_valid_position x y maze = x >= 0
&& y >= 0
&& x < length maze
&& y < length (maze !! 0)

保护条件也是将其分解的一种选择:

is_valid_position x y maze | x < 0 = False
| y < 0 = False
| x >= length maze = False
| y >= length (maze !! 0) = False
| otherwise = True

关于function - Haskell:if-then-else条件问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67806306/

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