Is there any fundamental limitations that stops Scala from implementing pattern matching over functions?

后端 未结 4 1833
不思量自难忘°
不思量自难忘° 2021-02-18 17:54

In languages like SML, Erlang and in buch of others we may define functions like this:

fun reverse [] = []
|   reverse x :: xs  = reverse xs @ [x];
4条回答
  •  借酒劲吻你
    2021-02-18 18:10

    There are at least two problems:

    1. [ and ] are reserved characters because they are used for type arguments. The compiler allows spaces around them, so that would not be an option.
    2. The other problem is that = returns Unit. So the expression after the | would not return any result

    The closest I could come up with is this (note that is very specialized towards your example):

    // Define a class to hold the values left and right of the | sign
    class |[T, S](val left: T, val right: PartialFunction[T, T])
    
    // Create a class that contains the | operator
    class OrAssoc[T](left: T) {
      def |(right: PartialFunction[T, T]): T | T = new |(left, right)
    }
    
    // Add the | to any potential target
    implicit def anyToOrAssoc[S](left: S): OrAssoc[S] = new OrAssoc(left)
    
    object fun {
    
      // Use the magic of the update method
      def update[T, S](choice: T | S): T => T = { arg =>
        if (choice.right.isDefinedAt(arg)) choice.right(arg)
        else choice.left
      }
    }
    
    // Use the above construction to define a new method
    val reverse: List[Int] => List[Int] =
      fun() = List.empty[Int] | {
        case x :: xs => reverse(xs) ++ List(x)
      }
    
    // Call the method
    reverse(List(3, 2, 1))
    

提交回复
热议问题