簡體   English   中英

Haskell類型錯誤(Int-> Bool函數參數)

[英]Haskell Type Error (Int -> Bool Function Parameter)

我正在嘗試遞歸地找到謂詞為true的第i個正整數。 我需要對每個功能保持通用。

ithTrueValue :: (Int -> Bool) -> Int-> Int
ithTrueValue func i
    | i < 1 = error "Integer MUST BE greater than 0" 
    | ithTrueValue func i = 1 + ithTrueValue(func i-1   )
    | otherwise = ithTrueValue(func i-1)

I get a type error:

ERROR file:.\new  10.hs:6 - Type error in guard
*** Term           : ithTrueValue func i
*** Type           : Int
*** Does not match : Bool

問題是ithTrueValue func i不是布爾值,而是整數。 我認為這里確實有4個案件需要處理,

  1. i是一個瘋狂的值,例如-1或類似值
  2. 謂詞在當前整數處為true,
  3. 謂詞在當前整數處為false
  4. 謂詞是真實的,這是i第一次是真的。

考慮到這一點,讓我們重新組織一下代碼

 ithTrueValue f i = go 0 f i

因此我們使用了名為go幫助程序函數,該函數將對整數進行計數並跟蹤我們所處的整數

    where go _    _ i | i <= 0 = error "i must be a positive integer" -- case 1.
          go curr f i | f curr = if i == 1
                                 then curr -- case 4. 
                                 else go (curr + 1) f (i - 1) -- case 2.
                      | otherwise = ??? -- case 3.

哪里??? 謂詞為假的情況。 我將留給您找出在這種情況下的處理方法。

現在可以使用,但是級別很低。 顯式遞歸並不是編寫此類排序的最佳方法。 更令人愉快的是依靠高階函數,特別是

 filter :: (a -> Bool) -> [a] -> [a]

因此,這將在列表中運行並保留謂詞為true的所有值

ithTrueValue i f = ??? filter f [0..]

哪里??? 得到列表的ith值。 為此,我們使用

(!!) :: [a] -> Int -> a

只是選擇一個索引

ithTrueValue i f = filter f [0..] !! i

您的錯誤是與此行:

    | ithTrueValue func i = 1 + ithTrueValue(func i-1   )
                                ^^^^^^^^^^^^^^^^^^^^^^^^^

iTruthValue接受2個參數,但是由於括號的緣故,您只能使用一個參數來調用它。

您可能想編寫類似以下內容的內容:

    | ithTrueValue func i = 1 + ithTrueValue func (i-1)

暫無
暫無

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

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