簡體   English   中英

Haskell-基本尾遞歸

[英]Haskell - Basic Tail Recursion

我有一個帶有參數的函數

whatIndex ::  (Eq a) => a -> [a] -> Integer

我在其中返回內部[a]的索引,從0開始,如果找不到,則返回-1。 這就是我寫的

module WhatIndex where

whatIndex ::  (Eq a) => a -> [a] -> Integer

whatIndex p [] = -1

whatIndex p (a:as) 
    | p==a = index
    | otherwise = whatIndex p as
    where index = 1+whatIndex p as

顯然,我在這里沒有正確增加索引。 知道為什么這行不通嗎? 另外,我無法更改參數。

========================

這是一些基本的輸入/輸出

whatIndex 3 [] = -1
whatIndex 2 [1,2,3,2,1]=1
whatIndex 1 [1,2,3,2,1]=0
whatIndex 'b' ['a' .. 'z']=1

1+whatIndex p as將遍歷所有剩余列表並計算它們,它不會給您索引。 只需使用這樣的迭代遞歸輔助函數...

您可以使用本地功能,也可以使用提升版本,這就是我在這里使用的功能。

whatIndex' ::  (Eq a) => Integer -> a -> [a] -> Integer

whatIndex' _ _ [] = -1

whatIndex' i p (x:xs) 
    | p == x = i
    | otherwise = whatIndex' (i+1) p xs

whatIndex p xs = whatIndex' 0 p xs

main = print $ whatIndex 'a' "bbbbaccc"

這是一個非尾遞歸版本:

whatIndex p (x:xs)
    | p == x = 0
    | otherwise = 1 + whatIndex p xs

尾遞歸是指一類遞歸函數,其中遞歸函數中的“最后”或“最終”函數調用是針對函數本身的。 因此,這意味着該函數不會在“尾部位置”(發生函數調用的最后一個位置)中調用其他函數(例如+ )。 您可以清楚地看到,在whatIndex的第一個版本中whatIndex的最終函數是whatIndex而在第二個版本(以whatIndex作為參數調用)中調用的最終函數是+

http://en.wikipedia.org/wiki/Tail_call

編輯:這是一個與您的規范更加接近的版本,盡管它有點混亂並且效率低下。

whatIndex p xs 
    | not (any (==p) xs) = -1
    | otherwise = whatIndex' p xs where
        whatIndex' p (x:xs)
            | p == x = 0
            | otherwise = 1 + whatIndex' p xs

如果要尾部遞歸,請嘗試使用累加器參數:

whatIndex :: (Eq a) => a -> [a] -> Integer
whatIndex =
  let whatIndex' count p [] = -1
      whatIndex' count p (a:as)
        | p==a = count
        | otherwise = whatIndex' (count + 1) p as
  in whatIndex' 0

暫無
暫無

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

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