(x:xs)模式Haskell逻辑 [英] (x:xs) pattern Haskell logic

查看:636
本文介绍了(x:xs)模式Haskell逻辑的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设有一个简单的函数:

  maximum'::(Ord a)=> [a]  - > 
maximum'(x:xs)= max x(maximum'xs)$ b $'b $ b maximum'[] = error b

我理解这个想法和什么(x:xs)。正如它在这里详细解释
什么当模式匹配?
时,圆括号表示(x:xs)吗?但是有一件事情我无法摆脱我的头脑。由于 cons :运算符将x附加到列表xs中,为什么x是函数参数列表的第一个元素,而xs是我们使用的尾部(x:xs)? 就像if(x:xs)在参数列表上调用头部和尾部一样。

解决方案

这只是一般模式的一个实例,一个类型的构造函数同时用于构造该类型的元素,解构。如果你写了

  data MyList a = Empty |你可以写一个(MyList a)





  maximum'::(Ord a)=> MyList a  - > (空x)=最大x(最大'xs)$ b最大'空'=错误'最大空列表'
最大'(缺x空)= x
最大' $ b

除了列表实际上等同于

  data [a] = [] | a:as 

就像其他数据类型一样,: code>用于构造和解构非空列表。


Let's say there is a simple function:

maximum' :: (Ord a) => [a] -> a  
maximum' [] = error "maximum of empty list"  
maximum' [x] = x  
maximum' (x:xs) = max x (maximum' xs)

I understand the idea and what (x:xs) does. As it was explained in details here What do the parentheses signify in (x:xs) when pattern matching? but there is one little thing that I cannot get out of my head. Since cons: operator appends x to a list xs, why is it that x is the first element of function argument list and xs is the tail when we use (x:xs)??? as if (x:xs) calls head and tail on argument list.

解决方案

This is just an instance of the general pattern that the constructor for a type is both used to construct elements of that type and to deconstruct. If you wrote

data MyList a = Empty | Cons a (MyList a)

you'd write

maximum' :: (Ord a) => MyList a -> a  
maximum' Empty = error "maximum of empty list"  
maximum' (Cons x Empty) = x  
maximum' (Cons x xs) = max x (maximum' xs)

Except that lists are actually defined equivalently to

data [a] = [] | a:as

so, just as with other data types, : is used both to construct and to deconstruct nonempty lists.

这篇关于(x:xs)模式Haskell逻辑的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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