我正在为家庭作业做转换问题,而且我是一个完整的Haskell新手,所以请耐心等待。在其中一个上,它要求我们尝试获取函数的类型:
fc :: (Bool, [Char]) -> Int -> Integer -> [Bool]
不用担心实际功能的作用或任何事情。这些函数不会运行,它只是一个测试,看看我们是否可以正确转换类型。到目前为止,我能得到的最远的是:
fc :: (Bool, [Char]) -> Int
fc (x, y) = ord (head y)
我将其转变为Int
。当我尝试使用Integer
函数将其变为toInteger
时,它会给我:
Couldn't match expected type `Int -> Integer'
with actual type `Integer'
In the return type of a call of `toInteger'
Probable cause: `toInteger' is applied to too many arguments
In the expression: toInteger (ord (head y))
有关新人的任何提示吗?
修改 我一直在努力参考的是:
fc :: (Bool, [Char]) -> Int -> Integer
fc (x, y) = toInteger (ord (head y))
我收到上述错误。
答案 0 :(得分:2)
您的类型签名错误。如果转换某些内容,则无法将其写入类型签名。只有最后一个是返回类型。其他是参数类型。 请遵循以下:
fc::(Bool,[Char])->Integer
fc (x,y) = toInteger . ord . head $ y
fc::(Bool,[Char])->Int->Integer--
fc (x,y) n = if n == w then n else w
where w = toInteger . ord . head $ y
编辑: 其他人提到如果你的老师期望它,那就说明什么是绝对正确的。但转换不会发生在类型符号中。
答案 1 :(得分:1)
早上好他说,这个想法正在被称为currying。基本上,在Haskell中,任何函数都只接受一个值并返回一个值:a -> b
。
所以,鉴于这个限制,我们如何实现像add这样需要两个参数的函数?答案是我们实现了一个带数字的函数,并返回另一个函数,它接受一个数字并返回一个数字。以这种方式解决这个问题可能会澄清事情:
add :: Int -> Int -> Int
add x = f where f y = x + y
(相当于add x y = x + y
,以及add = (+)
)。
在您的情况下,您应该仔细阅读错误:Couldn't match expected type Int -> Integer with actual type Integer In the return type of a call of toInteger
表示Haskell期望fc
返回类型Int -> Integer
的值,因为这是您的类型签名所说的,但是您提供的定义将始终生成Integer
类型的值。