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

时间:2015-12-22 19:51:48

标签: haskell

我是关于Haskell(以及Java)的新手,我试图找到解决我可能非常简单的问题的方法。我需要创建两个数组,它检查第一个数组是否是第二个数组的前缀,例如[5,6,7] [5,6,7,6,2]会给我布尔值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

1 个答案:

答案 0 :(得分:8)

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

-- 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