[英]Haskell: Order of evaluation for (++) and (:) operators
I have the following Haskell expression: 我有以下Haskell表达式:
3 : [40] ++ [50] ++ 5 : [60]
I would like to know how this expression is evaluated. 我想知道如何评估这个表达式。 Which operator has a higher precedence,
:
or ++
? 哪个运算符具有更高的优先级
:
或者++
? I think the result of the expression is [3,40,50,5,60], however I did this the following way: 我认为表达式的结果是[3,40,50,5,60],但是我这样做的方式如下:
3 : [40] ++ [50] ++ 5 : [60]
3 : [40] ++ [50] ++ [5,60]
3 : [40] ++ [50,5,60]
3: [40,50,5,60]
[3,40,50,5,60]
Is the above the correct way to evaluate the expression? 以上是评估表达式的正确方法吗? Any insights are appreciated.
任何见解都表示赞赏。
Both the (++) :: [a] -> [a] -> [a]
and (:) :: a -> [a] -> [a]
function have 5
as precedence , as we can read in the Haskell '10 report , and are right associative. (++) :: [a] -> [a] -> [a]
和(:) :: a -> [a] -> [a]
函数都有5
优先级 ,我们可以在Haskell '10报告 ,并且是正确的关联。
We can also obtain this data with :i
in the ghci
shell: 我们也可以使用以下命令获取此数据
:i
在ghci
shell中:
Prelude> :i (:)
data [] a = ... | a : [a] -- Defined in ‘GHC.Types’
infixr 5 :
Prelude> :i (++)
(++) :: [a] -> [a] -> [a] -- Defined in ‘GHC.Base’
infixr 5 ++
This thus means that: 这意味着:
3 : [40] ++ [50] ++ 5 : [60]
is short for: 是短的:
3 : ([40] ++ ([50] ++ (5 : [60])))
The (++)
operator is implemented as : (++)
运算符实现为 :
(++) :: [a] -> [a] -> [a] (++) [] ys = ys (++) (x:xs) ys = x : xs ++ ys
The (:)
is a data constructor, so that means it can not be "further evaluated". (:)
是一个数据构造函数,因此意味着它无法“进一步评估”。
This makes sense since it thus means that the ++
is here only applied to the tail, and hence as long as we are interested in the head, we do not need to evaluate that function. 这是有道理的,因为它意味着
++
只在这里应用于尾部,因此只要我们对头部感兴趣,我们就不需要评估该函数。 So a right associative (++)
is usually cheaper than a left associative (++)
although it will result in the same list. 因此,右关联
(++)
通常比左关联(++)
便宜,尽管它会产生相同的列表。
If we thus want to evaluate the full list, it is evaluated as: 如果我们想要评估完整列表,则将其评估为:
3 : ([40] ++ ([50] ++ (5 : [60])))
-> 3 : (40 : ([] ++ ([50] ++ (5 : [60]))))
-> 3 : (40 : ([50] ++ (5 : [60])))
-> 3 : (40 : (50 : ([] ++ (5 : [60]))))
-> 3 : (40 : (50 : (5 : [60])))
or more verbose: 或者更详细:
3 : ((40: []) ++ ((50 : []) ++ (5 : (60 : []))))
-> 3 : (40 : ([] ++ ((50 : []) ++ (5 : (60 : [])))))
-> 3 : (40 : ((50 : []) ++ (5 : (60 : []))))
-> 3 : (40 : (50 : ([] ++ (5 : (60 : [])))))
-> 3 : (40 : (50 : (5 : (60 : []))))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.