Haskell在嵌套函数定义中使用where定界 [英] Haskell scoping in nested function definitions using where

查看:162
本文介绍了Haskell在嵌套函数定义中使用where定界的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Haskell的范围在其中定义中存在问题。当我有以下函数 f 时,我想将 x 传递给本地定义的函数<$ c $没有明确地使用它作为参数,我得到一个错误,指出 x 的类型与输出中的类型不兼容 f1 ,但它应该是相同的:

 
f :: Eq a => a - > [a]
fx = f1 x
其中
f1 :: Eq a => a - > [a]
f1 y = [x,y]

错误如下:

 
无法匹配期望类型`a1'与推断类型'a'
`a1'是一个刚性类型变量,由
绑定test.hs中`f1'的类型签名:4:11
` a'是一个刚性类型变量,由
绑定,test.hs中为'f'的类型签名:1:8
在表达式中:x
在表达式中:[x,y]
在`f1'的定义中:f1 y = [x,y]
加载模块失败:没有。

当我将 x 作为附加参数传递时,就像我在下面的代码使用函数 g ,它工作正常:

 
g :: Eq a => a - > [a]
gx = g1 xx
其中
g1 :: Eq a => a - > a - > [a]
g1 xy = [x ,y]

有没有办法让中的类型位于<$与$ a (或 a1 )兼容的c $ c> f c $ c> f1 ?

解决方案

代码的问题是本地范围的f1类型签名。它指定f1可以采取任何类型

f1 :: Eq a => a - > [a]



尽管这是一个本地函数,但您已将此函数概括为能够采用不会存在于f中,无论这个函数接收HAS来自f,所以类型签名是不必要的。



只要删除f1类型的签名即可。



编辑:读我的帖子回到我自己,这有点不清楚。一个in f1是一个可以接受任何东西的参数化类型,但传递给它的参数已经在f中绑定了。所以这个函数只能接收它的父函数收到的东西,你给它的类型签名会违反这个规则。希望这个更清楚些。


I have a problem with Haskell's scoping in where definitions. When I have the following function f, where I want to pass the x to the locally defined function f1 without explicitely using it as a parameter, I get an error saying that the type of x is incompatible with the one in the output of f1, although it should be the same:

f :: Eq a => a -> [a]
f x = f1 x
    where
        f1 :: Eq a => a -> [a]
        f1 y = [ x, y ]

The error is the following:

    Couldn't match expected type `a1' against inferred type `a'
      `a1' is a rigid type variable bound by
           the type signature for `f1' at test.hs:4:11
      `a' is a rigid type variable bound by
          the type signature for `f' at test.hs:1:8
    In the expression: x
    In the expression: [x, y]
    In the definition of `f1': f1 y = [x, y]
Failed, modules loaded: none.

When I however pass the x as an additional parameter, as I did in the following code with the function g, it works fine:

g :: Eq a => a -> [a]
g x = g1 x x
    where
        g1 :: Eq a => a -> a -> [a]
        g1 x y = [ x, y ]

Is there a way to make the type a in f compatible to the type a (or a1) in f1?

解决方案

The problem with your code is the locally scoped f1 type signature. It specifies that f1 can take any type

f1 :: Eq a => a -> [a]

Even though this is a local function, you've generalized this function to be able to take a type that won't exist within f, whatever this function receives HAS to come from f, so the type signature is unnecessary.

Just remove the f1 type signature.

Edit: Read my post back to myself, it's a bit unclear. a in f1 is a parameterized type that can take anything, but the arguments passed to it are already bound in f. So this function can only receive what its parent function receives, the type signature you're giving it breaks that rule. Hope that's a little more clear.

这篇关于Haskell在嵌套函数定义中使用where定界的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆