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
Image of page 1
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.
Image of page 2
Parameterization of Sort The most flexible 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 ... }
Image of page 3
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)
Image of page 4
Parametrization with Ordered
Image of page 5
Image of page 6

You've reached the end of your free preview.

Want to read all 9 pages?

  • Fall '19

What students are saying

  • Left Quote Icon

    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.

    Student Picture

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

  • Left Quote Icon

    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.

    Student Picture

    Dana University of Pennsylvania ‘17, Course Hero Intern

  • Left Quote Icon

    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.

    Student Picture

    Jill Tulane University ‘16, Course Hero Intern

Stuck? We have tutors online 24/7 who can help you get unstuck.
A+ icon
Ask Expert Tutors You can ask You can ask You can ask (will expire )
Answers in as fast as 15 minutes
A+ icon
Ask Expert Tutors