多次使用参数的模式同义词中的定义发生冲突

问题描述 投票:0回答:2

为什么我不能定义这个模式同义词?

pattern Double a = (a,a)
error:
    • Conflicting definitions for ‘a’
      Bound at: <interactive>:1:21
                <interactive>:1:23
    • In a pattern synonym declaration
haskell pattern-synonyms
2个回答
0
投票

这只能通过相等比较元组的两个元素来实现,但模式不会自动生成用于此目的的

Eq
约束。

您可以通过在定义中使用视图模式来获得此功能:

{-# LANGUAGE PatternSynonyms, ViewPatterns #-}

fromRedunTuple :: Eq a => (a,a) -> Maybe a
fromRedunTuple (x,y)
 | x==y       = Just x
 | otherwise  = Nothing

pattern Double a <- (fromRedunTuple -> Just a)
 where Double a = (a,a)

0
投票

想象一下在函数定义中使用该模式,并调用它:

foo (a, a) = a

x = foo (7, 9)

您希望通过 RHS 上的

a
访问这两个值中的哪一个?
Double
也有同样的歧义——或者说如果允许的话就会有歧义。

也许您并不真的想在匹配位置使用

Double
,而只想构建?然后

double x = (x, x)

作为普通函数就可以了。

© www.soinside.com 2019 - 2024. All rights reserved.