gpt4 book ai didi

haskell - 在 haskell 中使用匿名与非匿名函数键入

转载 作者:行者123 更新时间:2023-12-04 14:53:36 24 4
gpt4 key购买 nike

为什么这个身份在我输入时会编译

f = (\x -> x) :: a -> a

但是这个没有?
f x = x :: a -> a

当我刚写
f x = x

并将其加载到 ghci 并输入 :t f 我收到
f :: p -> p

那么,不应该是一样的吗?

我收到的错误是

Couldn't match expected type ‘a1 -> a1’ with actual type ‘p’ because type variable ‘a1’ would escape its scope This (rigid, skolem) type variable is bound by an expression type signature: forall a1. a1 -> a1



我已经在谷歌上搜索了僵化的、skolem 的东西和错误,但它只给了我更多的问题。

最初我想编写一个函数,它接受两个输入并返回第一个,它只适用于匿名函数。所以我似乎对 lambdas 和打字缺乏一些了解。我仍处于学习 Haskell 的初期。
f = (\x y -> x) :: a -> b -> a

最佳答案

您应用类型签名 :: a -> ax ,而不是 f .您可以添加类型签名:

f :: a -> a; f x = x

但是,您不能指定 x:: a 类型无论如何,自从 a是与 a 不同的类型变量在外部类型签名中。您可以启用 ScopedTypeVariables [ghc-doc]扩展,以使用在外部范围中定义的类型变量,例如:
{-# LANGUAGE ScopedTypeVariables #-}

f :: forall a . a -> a
f x = x :: a

关于haskell - 在 haskell 中使用匿名与非匿名函数键入,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59175728/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com