使用尾递归查找给定元素的索引 [英] Finding the index of a given element using tail recursion
问题描述
我试图编写一个函数来使用尾递归来查找给定元素的索引。假设列表包含数字 1
到 10
,并且我正在搜索 5
,那么输出应该是 4
。我遇到的问题是使用尾递归计数。但是,我甚至不确定在这种情况下是否需要对递归调用的次数进行数量计数。我尝试使用 !!
,这没有帮助,因为它将元素返回到特定的位置。我需要这个函数来返回一个特定元素的位置(完全相反)。
我一直试图找出一个小时。
代码:
whatIndex a [] =错误无法搜索空列表
whatIndex a(x:xs)= foo a as
其中
foo m [] =错误空列表
foo m (y:ys)= if m == y then --get index of y
else foo m ys
注意:我试图在不使用库函数的情况下实现这个功能
您的帮助函数需要一个额外的参数
whatIndex a as = foo as 0
where
foo [] _ = error空列表
foo(y:ys)c
| a == y = c
|否则= foo ys(c + 1)
顺便说一句,给这个函数一个<$ code>可能返回类型而不是使用错误。这就是 elemIndex
的工作原理。这看起来像
whatIndex a as = foo as 0
where
foo [] _ = Nothing
foo(y:ys)c
| a == y =只需c
|否则= foo ys(c + 1)
I am trying to write a function to find the index of a given element using tail recursion. Lets say the list contains the numbers 1
through 10
, and I am searching for 5
, then the output should be 4
. The problem I am having is 'counting' using tail recursion. However, I am not even sure if I need to maunally 'count' the number of recursive calls in this case. I tried using !!
which does not help because it returns the element in a particular position. I need the the function to return the position of a particular element (the exact opposite).
I have been trying to figure this one out for a hours now.
Code:
whatIndex a [] = error "cannot search empty list"
whatIndex a (x:xs) = foo a as
where
foo m [] = error "empty list"
foo m (y:ys) = if m==y then --get index of y
else foo m ys
Note: I am trying to implement this without using library functions
Your helper function needs an additional parameter for the count.
whatIndex a as = foo as 0
where
foo [] _ = error "empty list"
foo (y:ys) c
| a == y = c
| otherwise = foo ys (c+1)
BTW, it's better form to give this function a Maybe
return type instead of using errors. That's how elemIndex
works too, for good reason. This would look like
whatIndex a as = foo as 0
where
foo [] _ = Nothing
foo (y:ys) c
| a == y = Just c
| otherwise = foo ys (c+1)
这篇关于使用尾递归查找给定元素的索引的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!