sml - Multiple input types with fold -
i trying figure out how implement fold functions on inputs of differing types. sample, i'll use count function list (though, have multiple functions implement this). assuming int list input (this should work type of list, though), count function be
val count = foldr (fn(x:int,y)=>y+1) 0 ; val count = fn : int list -> int however, attempting make count function type
val count = fn : int list * bool list -> int where int list universe of set, , bool determines values of universe in set. ie, (1,3,5,6),(true,false,false,true) results in final set of (1,6), have count of 2. first thought try form of
val count= foldr (fn(x:(int*bool),y)=>if #2x y+1 else y ) 0 ; but results in return type of
val count = fn : (int * bool) list -> int which not quite need. logically, similar, expected group 2 types in 1 list each.
you use
listpair.foldl:fun count (xs, bs) = listpair.foldl (fn (x, b, acc) => ...) ... (xs, bs)where first
...combination ofx,b,acc, second...initial value.this assumes
xs,bsequally long, , in case they're not, discards remaining elements in longer list. (you should try justify if gives correct answer in either casexsorbslonger.)otherwise, need combine (aka zip) int list × bool list (int × bool) list making function combines 2 lists, , use function in combination folding doing.
fun combine (x::xs, y::ys) = ... | combine (..., ...) = ...this function equivalent
listpair.zip.
Comments
Post a Comment