两个函数的ghci类型推断的差异

时间:2014-03-03 12:58:52

标签: haskell types type-inference ghci

我无法理解ghci在下面给出的示例中所做的类型推断的差异。即使它似乎

  • func1中,值listToUse被推断为类型listToUse :: [Integer] = _
  • func2中,listToUseval分别被推断为listToUse :: [a] = _val :: [a] = _类型。

代码是:

module Main where

mylist = 2:[3..]

func1 lst = 
  let listToUse = lst
  in listToUse          -- line 7

func2 lst = 
  let listToUse = lst
      val = 1:listToUse
  in val                -- line 12

main = do
  print $ take 4 $ func1 mylist
  print $ take 4 $ func2 mylist

我们可以通过放置断点并以下面显示的方式单步执行调试器来查看推论:

*Main> :t mylist
mylist :: [Integer]
*Main> :break 7
Breakpoint 0 activated at Test.hs:7:6-14
*Main> :break 12
Breakpoint 1 activated at Test.hs:12:6-8
*Main> main
Stopped at Test.hs:7:6-14
_result :: [Integer] = _
listToUse :: [Integer] = _
[Test.hs:7:6-14] *Main> :continue 
[2,3,4,5]
Stopped at Test.hs:12:6-8
_result :: [a] = _
val :: [a] = _
[Test.hs:12:6-8] *Main> :step
Stopped at Test.hs:11:13-23
_result :: [a] = _
listToUse :: [a] = _

0 个答案:

没有答案