interfacePriced<T>{fnprice[lent'x':<T>]->int32;}enumStock{out,few:int32,plenty}structItem{name:str.utf8,cents:int32[min0,max100_000],stock:Stock}fnprice[lent'i':Item]->int32{return'i'.cents;}fncheapest<T:Priced>[lent'xs':list[<T>]]-><T>orfail[empty]{iflist.length[lend'xs']equal_to0{failempty;}let'best':=1;for'k'from2tolist.length[lend'xs']by1{ifprice[lend'xs'[pos'k']]<price[lend'xs'[pos'best']]{change'best'='k';}}returncopy'xs'[pos'best'];}fndescribe[lent'i':Item]->str.utf8{let'dollars':=to.stored.str.utf8['i'.centsdiv.floor100]++"."++to.stored.str.utf8['i'.centsmod.floor100];match'i'.stock{out{return'i'.name++" — sold out";}few'n'{return'i'.name++" — only "++to.stored.str.utf8['n']++" left at $"++'dollars';}plenty{return'i'.name++" — $"++'dollars';}}}fnkeep[lent'xs':list[Item],'test':fn[lentItem]->bool]->list[Item]{let'out':list[Item]=[];for'x'inlend'xs'{if'test'[lend'x']{list.append[lend.mut'out',valuecopy'x'];}}returngive'out';}MAIN{let'shelf':=[Item[name="rope",cents=1_250,stock=Stock.plenty],Item[name="helmet",cents=8_999,stock=Stock.few[2]],Item[name="torch",cents=450,stock=Stock.out]];for'i'inlend'shelf'{std::print.stored[describe[lend'i'],newln];}let'limit':=5_000;let'affordable':=keep[lend'shelf',fn[lent'i':Item]->boolwith[lend'limit']{return'i'.centsat_most'limit';}];std::print.useful[list.length[lend'affordable']," affordable",newln];let'pick':=cheapest[lend'affordable']otherwisestd::exit[0];std::print.stored["cheapest: ",'pick'.name,newln];let'text':=std::input.line[]otherwisestr.empty;let'budget':=to.int32[min0,max100_000]['text']otherwise{not_a_number{std::print.stored["no budget given",newln];std::exit[0];}out_of_range{std::print.stored["budget must be 0..100000 cents",newln];std::exit[1];}};std::print.useful["budget ok: ",'budget',newln];}
Output
rope — $12.50
helmet — only 2 left at $89.99
torch — sold out
2 affordable
cheapest: torch
no budget given