0

我正在尝试获取列表中元素的索引。

但是我遇到的问题是当元素不在列表中时。

我在想也许尾递归是有序的,但我不确定如何去做。

whatIndex sought [] = -1
whatIndex sought (a:xs) = 
    if sought == a
        then 0
        else 1 + whatIndex sought xs

编辑:

当它不在列表中时,它应该返回 -1

例子:

whatIndex 3 [1,2,3] == 2
whatIndex 3 [0,1,2] == -1

编辑:能够让它工作。

4

1 回答 1

2

你当然有Data.List.findIndex。如果你想自己写,有很多方法,例如:

import Control.Monad

whatIndex x = msum . zipWith f [0..] where
  f i y = if x == y then Just i else Nothing

...返回一个Maybe Int. 如果您坚持使用 -1 hack,请在 . 前面添加fromMaybe (-1) $(来自) 。Data.Maybemsum

于 2013-02-13T14:57:31.963 回答