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

时间:2019-07-20 09:34:51

标签: haskell types

与haskell类型[*]混淆

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

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

我的目标

我正在关注Get programming with 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的出色回答),我可以理解问题。

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

  • 我通过s1构建了一个包含两个字符串s2i1和一个整数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。 之所以有效,是因为getS1getS2都将t的{​​{1}}绑定到ssiClosure

[Char]

访问字符和整数

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

这是我的理解:

  • 调用getS1S2_indirect ssiClosure = show (getS1 ssiClosure) ++ ", " ++ show(getS2 ssiClosure) 时需要getS1才能将其绑定到t
  • 调用[Char]时需要getI1才能将其绑定到t

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

Int

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

1 个答案:

答案 0 :(得分:5)

  

为什么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具有类型(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经常会推断出程序员不想要的类型,从而使代码看起来不正确。当推断出的类型与其余代码不匹配时,这通常会在以后的程序中引起令人困惑的类型错误。