gpt4 book ai didi

haskell - 在 Haskell 中创建一个简单的数组

转载 作者:行者123 更新时间:2023-12-05 09:21:05 25 4
gpt4 key购买 nike

我是 Haskell(和 Java)方面的新手,我试图为我可能非常简单的问题找到解决方案。我需要创建两个数组,检查第一个数组是否是第二个数组的前缀,例如 [5,6,7] [5,6,7,6,2] 会给我 bool 值 true。这是我尝试过的,但是我不知道如何声明一个数组。 n 应该是数组 a 的最高槽号,它向下计数。一旦 a 的一个槽不等于 b,它就应该返回 False。如果没有 n 变量,还有另一种实现它的方法吗?

isaprefix :: [Int] -> [Int] -> Int -> Bool
isaprefix a b n = if n==0
then True
else
if a[n] == b [n]
then isaprefix ((a[n-1]) (b[n-1]))
else False

最佳答案

是的,有。您使用模式匹配:

-- type signature can be slightly more general: any list of equatables.
isaprefix :: (Eq a) => [a] -> [a] -> Bool

-- first are the two "boring" cases.
-- we define that empty lists are prefixes of everything.
isaprefix [] _ = True

-- then: we also define that you can't be the prefix of an empty list.
isaprefix _ [] = False

-- those 2 are technically in conflict, so you need to know that the empty list is defined,
-- by the order of those definitions, to be a prefix of the empty list. This supports the
-- general property that `isprefixof x x == True` for all `x`.

-- ok, now here's the more interesting pattern: both lists are nonempty. We need them to
-- match on their first elements and also for the rest of the first list to prefix the
-- rest of the second list.
isaprefix (a:as) (b:bs)
| a == b = isaprefix as bs
| otherwise = False

关于haskell - 在 Haskell 中创建一个简单的数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34423444/

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