首页 文章

Haskell - 将多个函数传递给函数

提问于
浏览
-1

我试图测试将两个函数传递给'myfunc'来执行Int列表元素的操作 .

*这纯粹是为了测试 - 我知道我可以使用过滤器,甚至等等 . 只是在这里测试代码

addone :: Int -> Int
 addone i = i + 1
 addoone _ = 0

checkeven :: Int -> Bool
checkeven n 
   | even n == True = True
   | otherwise      = False

myfunc :: (Int -> Bool) -> (Int -> Int) -> [Int] -> [Int]
myfunc ce ao [] = []
myfunc _ ao (x : xs) = []
myfunc ce _ (x : xs) = []
myfunc ce ao (x : xs) = if ce x then ao x : tail else tail where
   tail = myfunc ce ao xs

mylist = [1,2,3,3,3,1,1,4]
main = do
  let x = myfunc checkeven addone mylist
  putStrLn $ show x

尝试运行“非详尽模式”时出错......有什么想法吗?

2 回答

  • 3

    在myfunc中,这两行是无用的,因为当模式匹配时它们意味着相同的事情(它们也不是你正在寻找的递归的最后阶段):

    myfunc _ ao (x : xs) = []
    myfunc ce _ (x : xs) = []
    

    也是在第一个模式匹配ce ao是无用的,因为它们不在任何地方使用,所以它们应该是_ .

    所以myfunc应该是这样的:

    myfunc :: (Int -> Bool) -> (Int -> Int) -> [Int] -> [Int]
    myfunc _ _ [] = []
    myfunc ce ao (x : xs) = if ce x then ao x : tail else tail where
       tail = myfunc ce ao xs
    
  • 1

    这是细分:

    addone :: Int -> Int
    addone i = i + 1
    addone _ = 0
    

    最后一行在这里是无关紧要的,因为第一行将匹配所有内容 .

    checkeven :: Int -> Bool
    checkeven n 
       | even n == True = True
       | otherwise      = False
    

    这可以写成 checkeven = even .

    myfunc :: (Int -> Bool) -> (Int -> Int) -> [Int] -> [Int]
    myfunc ce ao [] = []
    myfunc _ ao (x : xs) = []
    myfunc ce _ (x : xs) = []
    myfunc ce ao (x : xs) = if ce x then ao x : tail else tail where
       tail = myfunc ce ao xs
    

    匹配第1行的条件是“列表为空” . 匹配第2行和第3行的条件是“列表不为空” . 因此,第3和第4行永远不会匹配 .

    RE错误,我看不出它可以来自哪里 . 请发布重现问题的完整代码并清除错误消息 .

相关问题