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.

  1. you use listpair.foldl:

    fun count (xs, bs) = listpair.foldl (fn (x, b, acc) => ...) ... (xs, bs) 

    where first ... combination of x, b , acc , second ... initial value.

    this assumes xs , bs equally long, , in case they're not, discards remaining elements in longer list. (you should try justify if gives correct answer in either case xs or bs longer.)

  2. 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

Popular posts from this blog

javascript - jQuery: Add class depending on URL in the best way -

caching - How to check if a url path exists in the service worker cache -

Redirect to a HTTPS version using .htaccess -