Haskell类型定义==>等等 [英] Haskell type definition, => etc

查看:73
本文介绍了Haskell类型定义==>等等的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用了解Haskell"来学习Haskell.在第54页上,这样的实现:

I am learning Haskell using Learn You a Haskell. On page 54 is an implementation of take like so:

take' :: (Num i, Ord i) => i -> [a] -> [a]
take' n _
    | n <= 0 = []
take' _ []   = []
take' n (x:xs) = x : take' (n-1) xs

除了第一行,我了解所有代码.

I understand all the code apart from the first line.

我理解为::的部分意味着这是类型定义?

The :: part I understand as meaning this is a type definition?

(Num i,Ord i)是一个元组.元组的第一个元素必须是数字,足够公平.第二个参数必须能够订购.参数是相同的-都是i.这意味着类型必须相同吗?

(Num i, Ord i) is a tuple. The first element of the tuple has to be numeric, fair enough. the second param has to be able to be ordered. The parameter is the same - both are i. This means that the types have to be the same?

为什么不是(数字i,奥德j)?不是第二元组元素指清单?哪个可以是任何类型?

Why is it not (Num i, Ord j)? Isn't the 2nd tuple element referring to the list? Which could be of any type?

=>代表什么?

i-> [a]-> [a]表示第一个参数是数字吗?第二个参数是任意的类型列表,第三个参数是任何类型列表.所以这就是说第一个参数数值,第二个参数是任何类型的列表,它返回任何类型的列表类型.我想这是可以理解的.

i -> [a] -> [a] means first parameter is numeric? 2nd param is any type list, 3rd param is any type list. So this is saying first param numeric, 2nd param a list of any type and it returns a list of any type. Well that is understandable I suppose.

推荐答案

=> 之前的内容是约束.(Num i,Ord i)并不是通常意义上的元组.它指定了使用调用函数的任何特定类型 i 都必须存在类型类实例的要求.

The stuff before the => are constraints. (Num i, Ord i) isn't really a tuple in the usual sense. It specifies a requirement that type class instances exist for whatever specific type i you call the function with.

所以这种类型签名实际上是在说 take'的类型是 i->[a]->[a] ,但附加的限制是 i 必须具有 Num Ord 实例,这意味着您可以做一些基本的算术运算( Num 是数字"的缩写),然后比较哪个值更大( Ord 表示该类型的值已定义顺序,即可以对它们进行排序).

So what this type signature is actually saying is that the type of take' is i -> [a] -> [a], but with the additional restriction that i must have Num and Ord instances, which amounts to requiring that you can do some basic arithmetic (Num being short for "numeric" I suppose) and compare which value is larger (Ord meaning values of that type have an ordering defined, i.e. you can sort them or such).

在这种特殊情况下,比较 n< = 0 使用的是 Ord ,而减法和数字文字使用的是 Num .

In this particular case, the comparison n <= 0 is what uses Ord, while the subtraction and numeric literals use Num.

LYAH的第3章对此进行了介绍,而中提到了这些特定的类型类(除其他外)href ="http://learnyouahaskell.com/types-and-typeclasses#typeclasses-101">"Typeclasses 101"部分.

This is covered in chapter 3 of LYAH, and these specific type classes (among others) are mentioned in the Typeclasses 101 section.

这篇关于Haskell类型定义==>等等的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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