为什么高阶函数返回此(意外)类型?

詹斯

被haskell类型混淆[*]

我开始学习haskell,并且对haskells类型推断的结果感到困惑(请参见下面的示例)。不幸的是,我对Haskell的流利程度不足以提出真正的问题,因此我必须以身作则。

[*]一旦我知道了真正的问题,我将更新标题。

我的目标

我正在关注“使用haskell编程”一书。在第10课中,显示了一种“保持状态”的方法:


-- The result of calling robot (`r`) is a function that takes 
-- another function (`message` as argument). The parameters 
-- passed to the initial call to `robot` are treated 
-- as state and can be passed to `message`.
-- 
robot name health attack = \message -> message name health attack

getName r = r (\name _ _ -> name)

klaus = robot "Klaus" 50 5

*Main> getName klaus
"Klaus"

我想我了解它的要旨,并尝试创建一些机器人战斗。最后,我想要这样的东西:

klaus = robot "Klaus" 50 5
peter = robot "Peter" 50 5

victor = fight klaus peter

getName victor
-- should be "Klaus"

我的机器人

这是我写的实现:

robot name health attack = \message -> message name health attack

isAlive r = r (\_ health _ -> health > 0)

fight attacker defender = if isAlive attacker then
                             attacker
                          else
                             defender



printRobot r = r (\name health  attack -> "Name: " ++ (show name) ++", health: " ++ (show health) ++ ", attack: " ++ (show attack))

klaus = robot "Klaus" 50 5
peter = robot "Peter" 60 7

在ghci中进行实验

代码以ghci(:l robots.hs加载当我对代码进行试验时,我发现事情并没有按计划进行:类型系统和我对结果类型的外观似乎有不同的想法。

请指出我的推理错误的地方,并帮助我理解我的方式中的错误:-)

--
-- in ghci
--

*Main> :t klaus
-- I understood: 
-- klaus is a function. I have to pass a function that
-- takes name, health, and attack as parameters and 
-- returns something of type "t". 
--
-- A result of same type "t" is then returned by calling klaus
klaus :: ([Char] -> Integer -> Integer -> t) -> t

-- check the "isAlive" function:
-- As expected, it returns a Bool
*Main> :t isAlive klaus
isAlive klaus :: Bool

-- This is also expected as klaus has health > 0
*Main> isAlive klaus
True

-- Inspecting the type of `isAlive` confuses me:
--
-- I do understand:
--
-- The first parameter is my "robot". It has to accept a function
-- that returns a boolean (basically the isAlive logic):
--
-- (t1 -> a -> t -> Bool) 
-- - t1: name, ignored
-- - a: health, needs to be a comparable number 
-- - t: attack value, ignored
-- - returns boolean value if the health is >0
--
-- What I do NOT understand is, why doesn't it have the following type
-- isAlive :: (Ord a, Num a) => (t1 -> a -> t -> Bool) -> Bool
*Main> :t isAlive
isAlive :: (Ord a, Num a) => ((t1 -> a -> t -> Bool) -> t2) -> t2

-- The signature of `isAlive` bites me in my simplified 
-- fight club:
-- If the attacker is alive,  the attacker wins, else 
-- the defender wins:
fight attacker defender = if isAlive attacker then
                 attacker
              else
                 defender

-- I would expect the "fight" function to return a "robot".
-- But it does not:
*Main> victor = fight klaus peter
*Main> :t victor
victor :: ([Char] -> Integer -> Integer -> Bool) -> Bool

*Main> printRobot klaus
"Name: \"Klaus\", health: 50, attack: 5"
*Main> printRobot peter
"Name: \"Peter\", health: 60, attack: 7"
*Main> printRobot victor 

<interactive>:25:12: error:
    • Couldn't match type ‘[Char]’ with ‘Bool’
      Expected type: ([Char] -> Integer -> Integer -> [Char]) -> Bool
        Actual type: ([Char] -> Integer -> Integer -> Bool) -> Bool
    • In the first argument of ‘printRobot’, namely ‘victor’
      In the expression: printRobot victor
      In an equation for ‘it’: it = printRobot victor

问题

  • 为什么isAlive没有签名(t1 -> a -> t -> Bool) -> Bool
  • 我的fight功能出了什么问题

到目前为止我学到了什么

以我目前的理解,我无法解决问题,但是现在(由于@chi的出色回答),我可以理解问题。

对于所有其他陷入相同陷阱的初学者,以下是我对问题的简化版本的推理:

  • 我建一个封闭持有两个字符串s1s2和一个inti1通过buildSSIclosure通过将消息“发送”(传递函数)到闭包中,我可以访问闭包的“状态”。
  • 我可以写简单的存取getS1getS2getI1
  • 我想编写一个函数,该函数需要一个,并通过访问器ssiClosure获取Int[Char]属性。
-- IMPORTANT: the return value `t` is not bound to a specific type
buildSSIclosure :: [Char] -> [Char] -> Int -> ([Char] -> [Char] -> Int -> t) -> t
buildSSIclosure s1 s2 i1 = (\message -> message s1 s2 i1)

的定义buildSSIclosure没有t约束。当任何访问器的使用t所述的ssiClosure实例绑定到类型

getS1 :: (([Char] -> [Char] -> Int -> [Char]) -> [Char]) -> [Char]
getS2 :: (([Char] -> [Char] -> Int -> [Char]) -> [Char]) -> [Char]
getI1 :: (([Char] -> [Char] -> Int -> Int) -> Int) -> Int

-- `t` is bound to [Char]
getS1 ssiClosure = ssiClosure (\ s1 _ _ -> s1)

-- `t` is bound to [Char]
getS2 ssiClosure = ssiClosure (\ _ s2 _ -> s2)

-- `t` is bound to int
getI1 ssiClosure = ssiClosure (\ _ _ i1 -> i1)

我直接访问了lambda函数调用的两个参数。此方法有效,并将绑定t[Char]

getS1I1_direct ssiClosure = ssiClosure (\ s1 _ i1 -> s1 ++ ", " ++ show i1)

调用两个字符串访问器

我可以同时访问S1S2通过存取。这工作,因为这两个getS1,并getS2结合t来自ssiClosure[Char]

getS1S2_indirect ssiClosure = show (getS1 ssiClosure) ++ ", " ++ show(getS2 ssiClosure)

访问字符和整数

下一步是访问int和字符串属性。那甚至不会编译!

这是我的理解:

  • 来自闭包的调用getS1需求t将被绑定到[Char]
  • 来自闭包的调用getI1需求t将被绑定到Int

它不能绑定到两者,所以编译器告诉我:

getS1I1_indirect ssiClosure = show(getS1 ssiClosure) ++ ", "  ++ show(getI1 ssiClosure)

    • Couldn't match type ‘[Char]’ with ‘Int’
      Expected type: ([Char] -> [Char] -> Int -> Int) -> Int
        Actual type: ([Char] -> [Char] -> Int -> [Char]) -> [Char]
    • In the first argument of ‘getI1’, namely ‘ssiClosure’
      In the first argument of ‘show’, namely ‘(getI1 ssiClosure)’
      In the second argument of ‘(++)’, namely ‘show (getI1 ssiClosure)’

我仍然不必通过查看错误来识别问题。但是有希望;-)

开支

为什么isAlive没有签名(t1 -> a -> t -> Bool) -> Bool

isAlive r = r (\_ health _ -> health > 0)

让我们开始创建lambda。我想你可以看到

(\_ health _ -> health > 0) :: a -> b -> c -> Bool

b必须Ord>)和Num(必须为0

由于参数r将lambda作为输入,因此它必须是将lambda作为输入的函数:

r :: (a -> b -> c -> Bool) -> result

最后,isAliver作为参数,并返回与相同的结果r因此:

isAlive :: ((a -> b -> c -> Bool) -> result) -> result

添加约束并稍微重命名类型变量,我们得到GHCi的类型:

isAlive :: (Ord a, Num a) => ((t1 -> a -> t -> Bool) -> t2) -> t2

请注意,此类型比这更通用:

isAlive :: (Ord a, Num a) => ((t1 -> a -> t -> Bool) -> Bool) -> Bool

这大致意味着“给我一个Bool生成机器人,我给你一个Bool”。

我的fight功能出了什么问题

fight attacker defender = if isAlive attacker then
                 attacker
              else
                 defender

这很棘手。上面的代码将调用,isAlive attacker并强制attacker具有type (a -> b -> c -> Bool) -> result然后,result必须是Bool因为在中使用了它if而且,这使得defender具有相同的类型,attacker因为的两个分支都if then else必须返回相同类型的值。

因此,的输出fight必须是“Bool生成机器人”,即不再能够生成其他任何东西的机器人。

可以使用等级2类型解决此问题,但是如果您是初学者,建议您不要立即尝试使用。对于初学者来说,此练习相当先进,因为有很多lambda被传递。

从技术上讲,您到处都传递了教会编码的元组,而这仅适用于等级2多态性。通过一阶元组会容易得多。

无论如何,这是一个可能的解决方法。这将Klaus作为赢家打印

{-# LANGUAGE Rank2Types #-}

isAlive :: (Ord h, Num h) => ((n -> h -> a -> Bool) -> Bool) -> Bool
isAlive r = r (\_ health _ -> health > 0)

-- A rank-2 polymorphic robot, isomorphic to (n, h, a)
type Robot n h a = forall result . (n -> h -> a -> result) -> result

fight :: (Ord h, Num h) => Robot n h a -> Robot n h a -> Robot n h a
fight attacker defender = if isAlive attacker
   then attacker
   else defender

robot :: n -> h -> a -> Robot n h a
robot name health attack = \message -> message name health attack

printRobot :: (Show n, Show h, Show a) => ((n -> h -> a -> String) -> String) -> String
printRobot r = r (\name health  attack -> 
   "Name: " ++ show name ++
   ", health: " ++ show health ++
   ", attack: " ++ show attack)

klaus, peter :: Robot String Int Int
klaus = robot "Klaus" 50 5
peter = robot "Peter" 60 7

main :: IO ()
main = do
   let victor = fight klaus peter
   putStrLn (printRobot victor)

最后的笔记

我建议您将类型添加到每个顶级函数中。虽然Haskell可以推断出这些,但对于程序员来说,手头有类型非常方便。此外,如果您输入想要的类型,GHC将对其进行检查。GHC经常会推断出程序员不希望使用的类型,从而使代码看起来不正确。当推断出的类型与其余代码不匹配时,这通常会在程序稍后导致令人费解的类型错误。

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章