Purescript - 无法统一类型

nar*_*ama 3 unify purescript

我是Purescript(以及Haskell)的新手,我遇到了一个无法统一的错误.最初我有:

newtype Domain = Domain String

newtype Keyword = Keyword String

type Result = {
        domain    :: Domain,
        occurred   :: Boolean,
        position  :: Number,
        quality   :: Number
    }

is_min_pos :: Maybe Result -> Maybe Result -> Maybe Result
is_min_pos Nothing Nothing = Nothing
is_min_pos Nothing y = y
is_min_pos x Nothing = x
is_min_pos x y = if y.position < x.position then y else x     
Run Code Online (Sandbox Code Playgroud)

这给了我错误

Cannot unify type
  Prim.Object
with type
  Data.Maybe.Maybe
Run Code Online (Sandbox Code Playgroud)

我以为是因为期待x和y是Maybe Record类型.所以要明确我将代码改为,按类型进行模式匹配.

data Result = Result {
        domain    :: Domain,
        occurred   :: Boolean,
        position  :: Number,
        quality   :: Number
    }

is_min_pos (Result x) (Result y) = if y.position < x.position then y else x
Run Code Online (Sandbox Code Playgroud)

现在我收到了错误

Cannot unify type
  Data.Maybe.Maybe Processor.Result
with type
  Processor.Result
Run Code Online (Sandbox Code Playgroud)

这是指本节

y.position < x.position -- in the first case
Run Code Online (Sandbox Code Playgroud)

在第二种情况下

Result x -- on the pattern matching side
Run Code Online (Sandbox Code Playgroud)

我正在进一步努力

type Results = List Result

get_item_with_min_position :: Results -> Maybe Result
--get_item_with_min_position [] = Nothing
get_item_with_min_position results = foldl is_min_pos Nothing results
Run Code Online (Sandbox Code Playgroud)

我正在使用Foldable的'foldl'.我不知道如何模式匹配一​​个空列表.如果可以,我会将类型签名更改为

is_min_pos :: Maybe Result -> Result -> Maybe Result
Run Code Online (Sandbox Code Playgroud)

我现在得到错误

Cannot unify type
    Prim.Object
with type
    Data.Maybe.Maybe
Run Code Online (Sandbox Code Playgroud)

这是可以理解的,因为在

foldl is_min_pos Nothing results
Run Code Online (Sandbox Code Playgroud)

结果是类型列表结果is_min_pos期望可能结果

什么是解决这个问题的干净方法?

Phi*_*man 5

Maybe类型有两个数据构造函数:Nothing您正确匹配,和Just.如果你想匹配类型的东西Maybe a确实包含一个值,你应该匹配的Just构造函数.

您需要修改最终案例,如下所示:

is_min_pos (Just x) (Just y) = if y.position < x.position 
                                  then Just y 
                                  else Just x
Run Code Online (Sandbox Code Playgroud)

这里Just x有类型Maybe Result,根据类型签名是正确的,因此x有类型Result,所以你可以使用.position访问器来读取它的position属性.