非图解算器中的过滤器功能

时间:2019-05-22 16:46:38

标签: function haskell lambda filter higher-order-functions

我必须了解https://wiki.haskell.org/Nonogram

中的演绎求解器

我不知道

elim b w ps = filter (\p -> all (\x -> x `elem` p) b &&
                            all (\x -> x `notElem` p) w) ps

有效。我只知道

all (\x -> x `notElem` [1]) [1,2,3,4]

给出False

all (\x -> x `elem` [1]) [1,1,1,1]

给予True

但是我不知道运行所有elim函数及其工作原理很热

1 个答案:

答案 0 :(得分:3)

首先,帮助自己留一点空白以帮助理解,并命名子表达式:

elim b w ps = filter (\p -> all (\x -> x `elem`    p) b  &&
                            all (\x -> x `notElem` p) w
                       ) ps

            = filter foo ps
                where
                   foo p =  all (\x -> x `elem`    p) b  &&
                            all (\x -> x `notElem` p) w

            = filter foo ps
                where
                   foo p =  all tst1 b  &&  all tst2 w
                      where
                         tst1 = (\x -> x `elem`    p)
                         tst2 = (\x -> x `notElem` p)

            = filter foo ps
                where
                   foo p =  (&&)  (all tst1 b)  (all tst2 w)
                      where
                         tst1 x = elem    x p
                         tst2 y = notElem y p

现在该怎么办?还是更好,这是什么?让我们通过一些类型来建立我们的见解:

filter :: (a ->                Bool) -> [a] -> [a]
foo    ::  a ->                Bool
ps     ::                               [a]
filter    foo                           ps  :: [a]
p      ::  a
foo        p                :: Bool
(&&)        :: Bool -> Bool -> Bool
all tst1 b  :: Bool
all tst2 w  ::         Bool
---------------------------
all  :: (t -> Bool) -> [t] -> Bool
tst1 ::  t -> Bool
tst2 ::  t -> Bool
b    ::                [t]
w    ::                [t]
---------------------------
......
---------------------------
elim             b      w               ps  :: [a]
elim ::         [t] -> [t] ->           [a] -> [a]          

通过遍历tst1tst2的类型以找出ta类型之间的关系来完成图片。


tst1    ::         t        -> Bool          -- tst1 x = elem    x p
tst2    ::         t        -> Bool          -- tst2 y = notElem y p
x       ::         t
y       ::         t
elem    :: Eq t => t -> [t] -> Bool
notElem :: Eq t => t -> [t] -> Bool
p       ::              [t]                  -- it was : a !

因此a ~ [t][a] ~ [[t]],最后

elim             b      w               ps  :: [[t]]
elim :: Eq t => [t] -> [t] ->         [[t]] -> [[t]] 

因此,filter foo仅将p中的ps留在foo p == True中。

这意味着all tst1 b == True all tst2 w == True

这意味着x中的每个b都是p的元素,而y中的每个w不是 p中的元素。换句话说,p中只有这样的ps个被保留在

的结果列表中
foo p =  (b \\ p) == []   &&   (p \\ w) == p

按住:

import Data.List (\\)

elim b w ps = [ p | p <- ps, (b \\ p) == [], (p \\ w) == p ]