繁体   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