簡體   English   中英

我怎么把它變成尾遞歸? 哈斯克爾

[英]How would I turn this into a tail recursion? Haskell

我正在嘗試獲取列表中元素的索引。

但是我遇到的問題是元素不在列表中。

我想也許尾遞歸是有序的,但我不確定如何去做。

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

編輯:能夠讓它工作。

當然你有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黑客,加入fromMaybe (-1) $ (它來自Data.Maybe前方) msum

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM