繁体   English   中英

在Haskell中转换类型

[英]Converting types in Haskell

我正在研究作业的转换问题,并且是完整的Haskell新手,所以请耐心等待。 在其中之一上,它要求我们尝试使函数的类型为:

fc :: (Bool, [Char]) -> Int -> Integer -> [Bool]

不用担心实际功能是做什么的。 这些函数将不会运行,仅是测试,看是否可以正确转换类型。 到目前为止,我能得到的最远的是:

fc :: (Bool, [Char]) -> Int
fc (x, y) = ord (head y)

我在哪里将其转换为Int 当我尝试使用toInteger函数将其转换为Integer ,它给了我:

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))

我正在上面的错误。

您的类型签名错误。 如果您进行转换,则不能将其写入类型签名。 只有最后一个是返回类型。 其他是参数类型。 遵循这些:

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

编辑:其他人提到如果您的老师期望它是绝对正确的。 但是转换不会在类型符号中进行。

正如nm所说,这种想法被称为currying。 基本上,在Haskell中,任何函数都采用一个值并返回一个值: a -> b

因此,在有此限制的情况下,我们如何实现需要两个参数的加法等功能? 答案是我们实现了一个接受数字的函数,然后返回另一个接受数字并返回数字的函数 以这种方式进行布局可能会澄清一些问题:

add :: Int -> Int -> Int
add x = f where f y = x + y

(等效于add xy = 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类型的值Int -> Integer ,因为这就是您的类型签名所说的内容,但是您提供的定义将始终产生Integer类型的值。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM