FunSet Elmfold操作

问题描述

我正在尝试解决这个问题。

type alias FunSet = Int -> Bool          
contains : FunSet -> Int -> Bool   
contains set elem = set elem

singletonSet : Int -> FunSet  
singletonSet elem = \inputElem -> elem == inputElem

union : FunSet -> FunSet -> FunSet   
union a b = (\x -> (contains a x) || (contains b x))   

          

我的折叠功能应该执行以下操作: 获取集合列表并返回一个新集合,该集合通过使用operation函数应用折叠来构建。

fold: List FunSet -> ( FunSet -> FunSet -> FunSet ) -> FunSet
fold operation sets = 

示例:

(fold union [(singletonSet 1),(singletonSet 2),(singletonSet 3)]) 1 == True

我不清楚该怎么做。希望有人能帮忙^^

解决方法

您可以为此使用List.foldlList.foldr

fold sets f = 
  case sets of
    [] -> \_ -> False
    x :: xs -> List.foldl f x xs

我认为定义emptySet _ = False并直接使用List.foldl会更容易:

List.foldl union emptySet [(singletonSet 1),(singletonSet 2),(singletonSet 3)]

请注意,List.foldl的第一个参数是一个函数,该函数首先包含一个元素,然后是累加器,而不是相反,因此您不能简单地使用fold sets diff,必须使用fold sets (flip diff)来翻转参数。