# 5.3 Implicit Parameters.pdf - Implicit Parameters Making...

• No School
• AA 1
• 9

This preview shows page 1 - 6 out of 9 pages.

Implicit Parameters
Making Sort more General Problem: How to parameterize msort so that it can also be used for lists with elements other than Int ? def msort[ T ](xs : List [ T ]) : List [ T ] = ... does not work, because the comparison < in merge is not defined for arbitrary types T . Idea: Parameterize merge with the necessary comparison function.
Parameterization of Sort The most ﬂexible design is to make the function sort polymorphic and to pass the comparison operation as an additional parameter: def msort[ T ](xs : List [ T ])(lt : ( T , T ) => Boolean) = { ... merge(msort(fst)(lt), msort(snd)(lt)) } Merge then needs to be adapted as follows: def merge(xs : List [ T ], ys : List [ T ]) = (xs, ys) match { ... case (x :: xs1, y :: ys1) => if (lt(x, y)) ... else ... }
Calling Parameterized Sort We can now call msort as follows: val xs = List(-5, 6, 3, 2, 7) val fruit = List( ”apple” , ”pear” , ”orange” , ”pineapple” ) merge(xs)((x : Int , y : Int ) => x < y) merge(fruit)((x : String , y : String ) => x.compareTo(y) < 0) Or, since parameter types can be inferred from the call merge(xs) : merge(xs)((x, y) => x < y)
Parametrization with Ordered

#### You've reached the end of your free preview.

Want to read all 9 pages?

• Fall '19

### What students are saying

• As a current student on this bumpy collegiate pathway, I stumbled upon Course Hero, where I can find study resources for nearly all my courses, get online help from tutors 24/7, and even share my old projects, papers, and lecture notes with other students.

Kiran Temple University Fox School of Business ‘17, Course Hero Intern

• I cannot even describe how much Course Hero helped me this summer. It’s truly become something I can always rely on and help me. In the end, I was not only able to survive summer classes, but I was able to thrive thanks to Course Hero.

Dana University of Pennsylvania ‘17, Course Hero Intern

• The ability to access any university’s resources through Course Hero proved invaluable in my case. I was behind on Tulane coursework and actually used UCLA’s materials to help me move forward and get everything together on time.

Jill Tulane University ‘16, Course Hero Intern