首页 > 解决方案 > Haskell:如何将部分顺序应用于子字符串函数?

问题描述

我已经实现了类 POrd 和一个子字符串函数,它接受 2 个字符串并确定第一个字符串是否是第二个输入字符串的子字符串。

现在我想将 POrd 类应用到 substring 函数中,以便子字符串可以部分排序。

但是我被困在如何正确地将偏序类(POrd)应用到子字符串函数上。

 class Eq a => POrd a where

     pocompare :: a -> a -> Maybe Ordering
     (~<), (~>), (~<=), (~>=) :: a -> a -> Bool

       -- Minimal complete definition: (~<=) | pocompare
 
     pocompare x y | x == y       = Just EQ
                  | x ~<= y      = Just LT
                  | y ~<= x      = Just GT
                  | otherwise    = Nothing

     x ~<= y = pocompare x y ==  Just LT
     x ~<  y = x ~<= y && x /= y
     x ~>= y = y ~<= x
     x ~>  y = x ~>= y && x /= y

 substring :: Eq a => [a] -> [a] -> Bool
 substring []_= True
 substring _[]     = False
 substring p@(x:xs) (y:ys) = x == y && prefix xs ys || substring p ys
  where
    prefix []     _= True
    prefix _[]     = False
    prefix (a:as) (b:bs) = a == b && prefix as bs
 instance POrd a => POrd [a] where
  (~<=) = substring

  xs ~<= ys = substring xs ys
  xs ~>= ys = substring ys xs

标签: haskellsubstringpartial-ordering

解决方案


推荐阅读