简体   繁体   English

如何检查我正在处理Haskell中的列表?

[英]How to check that I'm dealing with a list in Haskell?

I'm learning Haskell, and I'm trying to add preconditions to a (trivial, as an exercise) element_at function (code below). 我正在学习Haskell,并且正在尝试将前提条件添加到(一个平凡的练习) element_at函数(下面的代码)。 I've created a "helper" elem_at_r because otherwise, len x fails at some point (when x is a 'literal' rather than a list? - I still have trouble parsing ghci's error messages). 我创建了一个“帮助程序” elem_at_r因为否则, len x有时会失败(当x是“文字”而不是列表时?-我仍然难以解析ghci的错误消息)。 elem_at now has all the error checking, and elem_at_r does the work. 现在, elem_at具有所有错误检查,而elem_at_r可以完成工作。 In elem_at , I'd like to add a check that x is indeed a list (and not a 'literal'). elem_at ,我想添加一个检查,以确保x确实是一个列表(而不是“文字”)。 How can I do that? 我怎样才能做到这一点?

len x = sum [ 1 | a <- x]

elem_at_r x n | n == 0     = head x
              | 0 < n      = elem_at_r (tail x) (n-1)

elem_at x n | x == []    = error "Need non-empty list"
            | len x <= n = error "n too large " ++ show (len x)
            | n < 0      = error "Need positive n"
            | otherwise  = elem_at_r x n  

Thanks! 谢谢!

Frank 坦率

Due to Haskell's type system, elem_at can only take a list as its first argument ( x ); 由于Haskell的类型系统, elem_at 只能将列表作为其第一个参数( x )。 if you try to pass a non-list, GHC will detect this and give an error at compile time (or interpretation time in GHCi). 如果您尝试传递非列表,则GHC将检测到该非列表,并在编译时(或GHCi中的解释时)给出错误。 I don't know why len would "fail"; 我不知道len为什么会“失败”。 could you post the error message that GHCi gives you? 您可以张贴GHCi给您的错误消息吗?

It looks like you were getting errors because of the "x == []" line. 似乎由于“ x == []”行而出现错误。 The code below pattern matches for that condition and adds a few signatures. 模式下面的代码针对该条件进行匹配,并添加一些签名。 Otherwise it is the same. 否则它是相同的。 Hope it helps. 希望能帮助到你。

len x = sum [ 1 | a <- x]

elem_at_r :: [a] -> Int -> a
elem_at_r x n | n == 0     = head x
              | 0 < n      = elem_at_r (tail x) (n-1)

elem_at :: [a] -> Int -> a
elem_at [] _ = error "Need non-empty list"
elem_at x n | len x <= n = error ("n too large " ++ show (len x))
            | n < 0      = error "Need positive n"
            | otherwise  = elem_at_r x n 

You could also make your helper functions part of this function using a where clause: 您还可以使用where子句将您的辅助函数纳入此函数:

elem_at :: [a] -> Int -> a
elem_at [] _ = error "Need non-empty list"
elem_at x n | len x <= n = error ("n too large " ++ show (len x))
            | n < 0      = error "Need positive n"
            | otherwise  = elem_at_r x n 
  where
    len :: [a] -> Int 
    len x = sum [ 1 | a <- x]

    elem_at_r :: [a] -> Int -> a
    elem_at_r x n | n == 0     = head x
                  | 0 < n      = elem_at_r (tail x) (n-1)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM