产生不同解释结果的等效函数

时间:2012-01-17 00:24:09

标签: haskell map lambda ghc ghci

背景:我正在调查匿名递归,我正在接受实现前奏的挑战而不使用任何命名递归只是为了帮助它在我的脑海里好好理解。我还没到那里,一路走来,我遇到了一些无关但仍然很有趣的东西。

map1     = \f -> \x -> if (tail x) == [] 
                       then [f (head x)] 
                       else f (head x) : (map1 f (tail x))

map2 f x =             if (tail x) == [] 
                       then [f (head x)] 
                       else f (head x) : (map2 f (tail x))

map3 f (x:xs) = if xs == [] then [f x] else f x : (map3 f xs)

map4 f (x:[]) = [f x]
map4 f (x:xs) =  f x : map4 f xs

GHC抱怨第一个,第二个是好的,第三个和第四个只是为了展示如何以不同的方式实现它们。

*Main> map1 (*2) [1..10]

<interactive>:1:15:
    No instance for (Num ())
      arising from the literal `10'
    Possible fix: add an instance declaration for (Num ())
    In the expression: 10
    In the second argument of `map1', namely `[1 .. 10]'
    In the expression: map1 (* 2) [1 .. 10]
*Main> map2 (*2) [1..10]
[2,4,6,8,10,12,14,16,18,20]
*Main> map3 (*2) [1..10]
[2,4,6,8,10,12,14,16,18,20]
*Main> map4 (*2) [1..10]
[2,4,6,8,10,12,14,16,18,20]

如果我向map1添加类型签名,那就很好了。

map1 :: Eq a => (a -> b) -> [a] -> [b]

前两个函数对我来说几乎是一样的,所以我想我的问题只是“这里发生了什么?”

2 个答案:

答案 0 :(得分:12)

你被monomorphism restriction咬了。任何写成foo = ...的东西 - 意味着定义没有参数,并且没有给出显式类型 - 必须根据此限制具有非泛型类型。如你所说,在这种情况下,泛型类型必须是Eq a => (a -> b) -> [a] -> [b],但由于单态限制适用,ab都被()取代,可以推断出可用类型变量的最简单类型。

答案 1 :(得分:6)

但是,如果您使用不受约束的null而不是(== [])

Prelude> let map0 = \f -> \x -> if null (tail x) then [f (head x)] else f (head x) : map0 f (tail x)
Prelude> :t map0
map0 :: (a -> t) -> [a] -> [t]
Prelude> map (*2) [1 .. 10]
[2,4,6,8,10,12,14,16,18,20]

它没有参数或签名。 只有受约束的类型变量才会受到单态限制

如果您将map1的定义放入文件并尝试编译或加载到ghci中,

Ambiguous type variable `a0' in the constraint:
  (Eq a0) arising from a use of `=='
Possible cause: the monomorphism restriction applied to the following:
  map1 :: forall t. (a0 -> t) -> [a0] -> [t] (bound at Maps.hs:3:1)
Probable fix: give these definition(s) an explicit type signature
              or use -XNoMonomorphismRestriction
In the expression: (tail x) == []
In the expression:
  if (tail x) == [] then
      [f (head x)]
  else
      f (head x) : (map1 f (tail x))
In the expression:
  \ x
    -> if (tail x) == [] then
           [f (head x)]
       else
           f (head x) : (map1 f (tail x))

ghci只是以它的方式抱怨,因为它使用ExtendedDefaultRules,否则你会得到一个可以理解的错误信息。

相关问题