Bool"与实际类型 "(Int,Bool)"匹配-6ren"> Bool"与实际类型 "(Int,Bool)"匹配-我正在编写一个简单的代码,以将列表中具有正确条件的数字添加到新列表中。但是我收到一个错误,其中一个输入是 (Int, Bool) 而不是 Int,这是怎么发生的?这是我正在编写的代码 module F-6ren">
gpt4 book ai didi

haskell - 无法将 "Int -> Bool"与实际类型 "(Int,Bool)"匹配

转载 作者:行者123 更新时间:2023-12-05 01:24:48 25 4
gpt4 key购买 nike

我正在编写一个简单的代码,以将列表中具有正确条件的数字添加到新列表中。但是我收到一个错误,其中一个输入是 (Int, Bool) 而不是 Int,这是怎么发生的?这是我正在编写的代码

module FilterList where

-- Definisi dan Spesifikasi
countIf :: [Int] -> (Int,Bool) -> [Int]
{-Mencari elemen yang memenuhi kriteria tertentu-}
isPos :: Int -> Bool
{-True jika positif-}
isNeg :: Int -> Bool
{-True jika negatif-}
isKabisat :: Int -> Bool
{-True jika berada pada tahun kabisat (dapat dibagi 4 atau 400 tetapi tidak bisa dibagi 100)-}
isEmpty :: [Int] -> Bool
{-True jika list kosong-}

-- Realisasi
isEmpty li = (length li) == 0
isPos a = a >= 0
isNeg a = a < 0
isKabisat a = (mod a 4) == 0 && ((mod a 100) /= 0 || (mod a 400) == 0)
countIf li func
| isEmpty li = []
| func (head li) = [] ++ [head li] ++ countIf (tail li) func
| otherwise = [] ++ countIf (tail li) func

有些东西是印度尼西亚语,但只在评论中,所以总体思路仍然存在。

最佳答案

签名错误:func 是谓词,所以:

countIf :: [Int] -> (<strong>Int -> Bool</strong>) -> [Int]

您的 isEmpty 函数等同于 null :: Foldable f => f a -> Bool (效率更高),countIffilter :: (a -> Bool) -> [a] -> [a] 的“翻转”版本的特殊版本.名称 countIf 还表明您正在计算匹配元素的数量,而不是与谓词匹配的项目列表。

使用 []++ xs 没有多大意义:这将简单地返回 xs,而 [x]++ ys 是相当于 x : ys。您使用模式匹配来避免使用 headtail,因此:

countIf :: [a] -> (a -> Bool) -> [a]
countIf [] func = []
countIf (h:t) func
| func h = h : countIf t func
| otherwise = countIf t func

但是 countIf 可以这样实现:

countIf :: [a] -> (a -> Bool) -> [a]
countIf = flip filter

关于haskell - 无法将 "Int -> Bool"与实际类型 "(Int,Bool)"匹配,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/71157472/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com