简体   繁体   English

Haskell类型错误(Int-> Bool函数参数)

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

I'm trying to recursively find the ith positive integer for which the predicate is true. 我正在尝试递归地找到谓词为true的第i个正整数。 I need to keep it general for every function. 我需要对每个功能保持通用。

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

The problem is that ithTrueValue func i isn't boolean, it's an integer. 问题是ithTrueValue func i不是布尔值,而是整数。 I think there are really 4 cases to deal with here, 我认为这里确实有4个案件需要处理,

  1. i is an insane value, like -1 or similar i是一个疯狂的值,例如-1或类似值
  2. The predicate is true at the current integer, 谓词在当前整数处为true,
  3. The predicate is false at the current integer 谓词在当前整数处为false
  4. The predicate is true and this is the i th time it's true. 谓词是真实的,这是i第一次是真的。

With that in mind let's restructure your code a bit 考虑到这一点,让我们重新组织一下代码

 ithTrueValue f i = go 0 f i

so we're using this helper function called go which is going to count up the integers and keep track of what integer we're at 因此我们使用了名为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.

Where ??? 哪里??? is the case where the predicate is false. 谓词为假的情况。 I'll leave it to you to figure out what to do in this case. 我将留给您找出在这种情况下的处理方法。

Now this works, but it's very.. low level. 现在可以使用,但是级别很低。 Explicit recursion is not the nicest way to write this sorta stuff. 显式递归并不是编写此类排序的最佳方法。 More pleasant is to rely on higher order functions, specifically 更令人愉快的是依靠高阶函数,特别是

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

So this will run down the list and leave all values where the predicate is true 因此,这将在列表中运行并保留谓词为true的所有值

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

where ??? 哪里??? get's the ith value of the list. 得到列表的ith值。 For this we use 为此,我们使用

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

which just selects an index 只是选择一个索引

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

Your error is with this line: 您的错误是与此行:

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

iTruthValue takes 2 arguments, but because of the parens you're only calling it with one. iTruthValue接受2个参数,但是由于括号的缘故,您只能使用一个参数来调用它。

You probably wanted to write something like: 您可能想编写类似以下内容的内容:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM