将列表添加到空包中

时间:2015-10-21 22:42:26

标签: haskell

我正在尝试将一个无序列表(如[2,1,5,4,3])添加到行李中,可以将其视为空列表。

这是我的代码:

module Bags where

import Data.List
import Prelude

-- | Bag datatype
type Bag a = [a]

-- | Empty bag
emptyBag :: Bag a
emptyBag = []

-- | Put all elements from a list into a bag.
listToBag :: Bag a -> [a] -> Bag a
listToBag xs = foldr (\x bag -> bagInsert bag x) emptyBag xs

将元素插入列表的功能如下所示

-- | Add an element to a bag.
bagInsert :: Bag a -> a -> Bag a
bagInsert b = (insert (+) emptyBag)

但是,insert函数适用于有序元素。在那里,我可以添加这些元素,而无需重新安排他们的元素'列表中各自的位置?

1 个答案:

答案 0 :(得分:0)

当然可以:

module Bags where

type Bag a = [a]

emptyBag :: Bag a
emptyBag = []

listToBag :: Bag a -> [a] -> Bag a
listToBag = foldr (:)

bagInsert :: Bag a -> a -> Bag a
bagInsert = flip (:)

表达式listToBag emptyBag [2,1,5,4,3]计算到包[2,1,5,4,3]