Haskell - 使用 foldr 为函数 `all` 创建函数定义

max*_*loo -2 haskell predicate fold

我正在尝试all使用foldr. p是谓词。我知道这是可以做到的:

all p = and . foldr (\x xs -> p x : xs) []
Run Code Online (Sandbox Code Playgroud)

但我想做的是将函数and转换为foldr方程。这能做到吗?

我尝试了以下方法,但都失败了:

all p = foldr (\x p -> \ys -> and (p x) ys) True
all p = foldr (\x and -> (\ys -> (p x and ys))) True
all p = foldr (\x ys -> and . (p x) ys) True
Run Code Online (Sandbox Code Playgroud)

我对如何申请的理解不足foldr吗?

Wil*_*ess 5

我们有

all p = and 
         . foldr (\x xs -> p x :  xs) []    
      = foldr                 (&&)   True   -- {y : ys} -> y && {ys}      2-3
         . foldr (\x xs -> p x :  xs) []    -- {x , xs} -> p x : {xs}   1-2
      =    foldr (\x xs -> p x && xs) True  -- {x , xs} -> p x && {xs}  1---3
Run Code Online (Sandbox Code Playgroud)

因为折叠替换每个构造与指定的组合操作(又名减速器),和更换缺点 用的元件的缺点的改性元素的,然后代替该缺点(&&),只是更换缺点与所述元素的(&&)改性的立即元素:

    a  : (  b  : (  c  : (  d  : ( ... ))))   _OR_   []      --   |       |   1
                                                             --   |       |
  p a  : (p b  : (p c  : (p d  : ( ... ))))   _OR_   []      --   ?   |   |   2
                                                             --       |   |
  p a && (p b && (p c && (p d && ( ... ))))   _OR_  True     --       ?   ?   3
Run Code Online (Sandbox Code Playgroud)

换句话说,folds 通过融合它们的 reducer 函数来组合,reducer 函数通过用折叠链中下一个 fold 的 reducer 替换 {constructors they use} 来融合,从而组成它们对应的转换器(如在 Clojure 的转换器中);因此,

 = foldr              (reducingWith (&&)) True
     . foldr ((mapping p)    (:))           []
 = foldr ((mapping p) (reducingWith (&&))) True
 = foldr ((mapping p . reducingWith) (&&) ) True
   -- first map p, then reduce with (&&)
Run Code Online (Sandbox Code Playgroud)

为适当的定义reducingWithmapping

reducingWith cons x xs = cons x xs
mapping f cons x xs = cons (f x) xs
filtering p cons x xs | p x = cons x xs
                      | otherwise = xs
concatting t cons x xs = foldr cons xs (t x)
Run Code Online (Sandbox Code Playgroud)