Skip to content

Conversation

rvilla87
Copy link
Contributor

@rvilla87 rvilla87 commented Nov 3, 2018

You have to add result type in order to call insertionSort as stated in "Calling Parameterized Sort".

You have to add result type in order to call insertionSort as stated in "Calling Parameterized Sort".
@FRosner
Copy link
Member

FRosner commented Nov 5, 2018

Does the code compile now after your change? Can you please include the original error message and an example of the code that caused it?

@rvilla87
Copy link
Contributor Author

rvilla87 commented Nov 5, 2018

Yes, I will explain it in detail.

The first code of insertionSort works correctly but when trying to apply the changes stated in "Parameterization of Sort" it throws this error:

recursive method insertionSort needs result type
    case y :: ys => insert(y, insertionSort(ys)(lessThan))

The modified code that returns this error is:

def insertionSort[T](xs: List[T])(lessThan: (T, T) => Boolean) = {
    def insert(y: T, ys: List[T]): List[T] =
    ys match {
      case List() => y :: List()
      case z :: zs =>
        if (lessThan(y, z)) y :: z :: zs
        else z :: insert(y, zs)
    }

  xs match {
    case List() => List()
    case y :: ys => insert(y, insertionSort(ys)(lessThan))
  }
}

Now, if we apply the fix it works correctly (adding : List[T] ):

def insertionSort[T](xs: List[T])(lessThan: (T, T) => Boolean): List[T] = {
    def insert(y: T, ys: List[T]): List[T] =
    ys match {
      case List() => y :: List()
      case z :: zs =>
        if (lessThan(y, z)) y :: z :: zs
        else z :: insert(y, zs)
    }

  xs match {
    case List() => List()
    case y :: ys => insert(y, insertionSort(ys)(lessThan))
  }
}

We can call it correctly as stated in the exercise:
insertionSort(nums)((x: Int, y: Int) => x < y)

@FRosner
Copy link
Member

FRosner commented Nov 6, 2018

Thank you!

@FRosner FRosner merged commit 15d34e0 into scala-exercises:master Nov 6, 2018
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants