Untitled

 avatar
unknown
scala
a year ago
2.8 kB
5
Indexable
object Main extends App {

    // Ejercicio 1

    def firstp[A](obj: A, list: List[A]): Boolean = {
        list match {
            case h :: _ if(obj==h) => true
            case _ => false
        }
    }
    println(firstp('a', List('a', 'b', 'c')))

    // Ejercicio 2

    def duplicar[A](list: List[A]): List[List[A]]= {
        list match {
            case Nil => Nil
            case h :: Nil => List(List(h, h))
            case h :: tail => List(h, h) :: duplicar(tail)
            case _ => throw new NoSuchElementException
        }
    }
    println(duplicar(List('a', 'b', 'c')))

    // Ejercicio 3

    def countdown(N: Int): List[Int] = {
        N match {
            case 1 => List(1)
            case n => n :: countdown(n-1)
            // case _ => throw new Exception // unreachable, mejor quitarlo
        }
    }
    println(countdown(10))

    // Ejercicio 4

    def reverse[A](list: List[A]): List[A] = {
        list match {
            case Nil => throw new Exception
            case h :: Nil => List(h)
            case h :: tail => reverse(tail) :+ h
            case _ => throw new Exception
        }
    }
    println(reverse(List(1,2,3)))

    // Ejercicio 5
    
    def substitute[A](x: A, y: A, ls: List[A]): List[A] = {
        ls match {
            case h :: tail if(h==y) => x :: substitute(x, y, tail)
            case h :: tail => h :: substitute(x, y, tail)
            case Nil => Nil
            case other => other
            // c
            // case Nil => Nilase _ => throw new Exception // code unreachable
        }
    }
    println(substitute('a', 'b', List('a', 'b', 'c')))

    // Ejercicio 6 WIP  

    // def setequal[A](ls1: List[A], ls2: List[A]): Boolean = {
    //     (ls1, ls2) match {
    //         case (h1 :: tail1, h2 :: tail2) if(h1==h2) => setequal(tail1, ls2)
    //         case (h1 :: tail, h2 :: tail2) if(h1!=h2) => setequal(tail1, tail2)
    //         case (h1 :: tail, h2 :: tail2) 
    //         case (Nil, h2 :: tail2) =>  
    //     }
    // }
    // println(setequal(List(1, 1, 2), List(1, 2)))

    // def getSet[A](list: List[A]): List[A] = {
    //     list match {
    //         case h :: Nil => List(h)
    //         case Nil => Nil
    //         case h :: j :: tail if(h==j) => h :: getSet(tail)
    //         case h :: tail => h :: getSet(tail)
    //         case _ => throw new Exception
    //     }
    // }
    // println(getSet(List('a','a','b','c','c')))

    // Ejercicio 7

    def impares[A](list: List[A]): List[A] = {
        list match {
            case a :: b :: tail => a :: impares(tail)
            case a :: Nil => List(a)
            case Nil => Nil
            case _ => throw new Exception 
        }
    }
    println(impares(List(1,2,3,4,5,6)))
}
Editor is loading...
Leave a Comment