function Promise.fold(P,G,w)assert(type(P)=="\116\097\098\108\101","\066\097\100 \097\114\103\117\109\101\110\116 \035\049 \116\111 \080\114\111\109\105\115\101\046\102\111\108\100\058 \109\117\115\116 \098\101 \097 \116\097\098\108\101")assert(type(G)=="\102\117\110\099\116\105\111\110","\066\097\100 \097\114\103\117\109\101\110\116 \035\050 \116\111 \080\114\111\109\105\115\101\046\102\111\108\100\058 \109\117\115\116 \098\101 \097 \102\117\110\099\116\105\111\110")local U=Promise.resolve(w)return(Promise.each(P,function(P,w)U=U:andThen(function(U)return G(U,P,w)end)end)):andThenReturn(U)end

function Promise.fold(list, callback, initialValue)
	assert(type(list) == "table", "Bad argument #1 to Promise.fold: must be a table")
	assert(type(callback) == "function", "Bad argument #2 to Promise.fold: must be a function")

	local accumulator = Promise.resolve(initialValue)
	return Promise.each(list, function(resolvedElement, i)
		accumulator = accumulator:andThen(function(previousValueResolved)
			return callback(previousValueResolved, resolvedElement, i)
		end)
	end):andThenReturn(accumulator)
end
