在Haskell中,如何在不使用前奏函数长度或(!!)的情况下提取列表的第七个元素。
以下是我目前的情况:
element7 :: [a] -> Int -> a
element7 [] _ = error "list too short"
element7 (_:xs) 7 = element7 xs (k - 1)
答案 0 :(得分:7)
seventh (one:two:three:four:five:six:seven:rest) = seven
答案 1 :(得分:4)
好吧,让我们从我们拥有的东西开始
element :: [a] -> Int -> a
element [] _ = error "list too short"
element (_:xs) 7 = element7 xs (k - 1)
现在最后一个案例是我们7岁的时候,但我们真的对任何大于0的数字感兴趣
element (x:xs) n | n > 0 = element xs (n-1)
然后如果n
为1,我们只返回头
element (x:xs) n | n > 0 = element xs (n-1)
| n == 0= x
| otherwise = error "Index out of range"
现在我们只需创建一个很好的快捷方式来查找第7个元素:
seventh xs = element xs 6
答案 2 :(得分:1)
这是另一个版本,它删除给定字符串的前六个字母,然后返回余数的第一个字母:
seventh = head . drop 6
答案 3 :(得分:0)
此解决方案试图更接近您的尝试:
element :: [a] -> Int -> a
element [] _ = error "list too short"
element (x:_) 1 = x
element (_:xs) i = element xs (k - 1)