记录类型的默认相等?

时间:2018-04-15 16:06:08

标签: purescript

我正在 The Purescript Book 的第3章末尾做这个练习:

  

通过重用findEntry中的现有代码,编写一个查找给定街道地址的条目的函数。在PSCi中测试你的功能。

我试过了:

findByAddress address = head <<< filter filterEntry
  where
    filterEntry :: Entry -> Boolean
    filterEntry entry = entry.address == address

错误:

  No type class instance was found for

    Data.Eq.Eq { street :: String
               , city :: String  
               , state :: String 
               }                 


while applying a function eq
  of type Eq t0 => t0 -> t0 -> Boolean
  to argument entry.address
while inferring the type of eq (entry.address)
in value declaration findByAddress

问题1:我认为记录类型具有默认的相等功能,即所有记录属性都相等。有吗?我该如何使用它?

问题2:如果我在问题1中的假设是假的,我试过:

eq :: Address -> Address -> Boolean 
eq address1 address2 = address1.street == address2.street &&
                       address1.city == address2.city &&
                       address1.state == address2.state

但这并没有解决问题。为什么不呢?

1 个答案:

答案 0 :(得分:3)

bower install purescript-record-extra

pulp repl
> import Data.Record.Extra (eqRecord)

> {a:1, b:2.5} `eqRecord` {a:1, b:2.5}
true

> {a:1, b:2.5} `eqRecord` {a:1, b:3.5}
false

-- different record types cannot be compared

> {a:1, b:2.5} `eqRecord` {a:1, b:3.5, c:"abc"}
Error found:
in module $PSCI
at  line 1, column 25 - line 1, column 45

  Type of expression contains additional label c.

while checking that expression { a: 1    
                               , b: 3.5  
                               , c: "abc"
                               }         
  has type { a :: Int   
           , b :: Number
           }            
while applying a function ((eqRecord (#dict RowToList t2 t1)) (#dict EqRecord t1 t2)) { a: 1  
                                                                                      , b: 2.5
                                                                                      }       
  of type { | t0 } -> Boolean
  to argument { a: 1    
              , b: 3.5  
              , c: "abc"
              }         
in value declaration it

where t0 is an unknown type

更新pkg purescript-record有一个相等的操作。

> import Data.Record (equal)
> {a:1, b:2.5} `equal` {a:1, b:2.5}
true

> {a:1, b:2.5} `equal` {a:1, b:3.5}
false

> {a:1, b:2.5} `equal` {a:1, b:2.5, c:"abc"}
Error found:
in module $PSCI
at  line 1, column 22 - line 1, column 42

  Type of expression contains additional label c.

while checking that expression { a: 1    
                               , b: 2.5  
                               , c: "abc"
                               }         
  has type { a :: Int   
           , b :: Number
           }

使用 newtypes 派生实例

> newtype Address = Address {street::String, city::String}

> derive instance eqAddress :: Eq Address

> Address {street:"la Rambla", city:"Barcelona"} == Address {street:"main", city:"LA"}
false