Download Presentación
Document related concepts
no text concepts found
Transcript
PARADIGMAS FP Y OOP USANDO TÉCNICAS AVANZADAS DE PROGRAMACIÓN ASÍNCRONA Cátedra Capgemini 2016/17 - Universitat de València a la innovación en el desarrollo de Software 2 Me presento ... Víctor M. Bolinches Software Architect en Capgemini. Founder Programmer en PlayGram Games. Ninja Developer en Indie VideoGames Development. Github vicboma1 Linkedin victorbolinches Twitter @vicboma1 Conceptos Básicos Abstracciones semánticas 3 4 Paradigmas de Programación ▹ OOP ▸ Estructura de datos llamados objetos ▸ Aglutinan propiedades y métodos ▸ Manipula datos de entrada para generar datos de salida específicos ▹ FP ▸ ▸ ▸ ▸ Estructura mediante expresiones Variables sin estado e inmutables Recursión y Funciones de primer orden Definición de cómputos y cálculo de lambdas 5 ” 6 Objeto inmutable ▹ Objeto cuyo estado no puede ser modificado ▹ Seguridad de trabajo en proceso Multihilos ▹ Java/C#: String, Integer, Long, Short… ▹ Scala : val (keyword) ▹ C++ : “const” 7 Lambdas ▹ Bloque de código abstracto ▹ Procesamiento inline ▸ Árboles de decisión ▸ Delegados ▹ Parámetros de entrada y salida ▹ Inferencia de tipos 8 Lambdas class A { public void foo() { Arrays.asList(1,2,3,4,5,6).forEach( s -> { System.out.println(s); } ); } } ...eq class A { public void foo() { Arrays.asList(1,2,3,4,5,6).forEach( [lambda for lambda$1 as Block] ); } static void lambda$1(String s) { System.out.println(s); return; } 9 Traits ▹ Tipos abstractos ▹ Modelo conceptual simple ▹ Incluye definición de métodos 10 Traits - Mejores prácticas por composición public class BaseClass { protected Logger logger = LoggerFactory.getLogger(this.getClass()); @Override public Integer foo() { logger().info("foo…!!!!"); } } ... public interface Loggable { default Logger getLogger(){ return LoggerFactory.getLogger(this.getClass()); } public class BaseClass implements Loggable , Comparable … { @Override public Integer foo() { } getLogger().info("foo…!!!!"); } 11 Mixins ▹ ▹ ▹ ▹ Clase abstractas Modelo conceptual simple Puede guardar el estado de un objeto Clase base no tiene control sobre la composición del mixin 12 Mixins public class abstract AbstractClass { protected Logger logger = LoggerFactory.getLogger(this.getClass()); @Override public Integer foo() { logger().info("foo…!!!!"); } } ... public interface Loggable { default Logger getLogger(){ return LoggerFactory.getLogger(this.getClass()); } } public class abstract AbstractClass implements Loggable { protected Integer LoggerInfoFoo() { getLogger().info("foo…!!!!"); } } public class BaseClass extends AbstractClass { ... 13 Comunicación entre procesos ▹ Síncrono ▸ Intercambio de información en tiempo real ▹ Concurrente ▸ Ejecución simultánea de tareas en tiempo real ▹ Paralelo ▸ Sistema multi-procesado (subdominio concurrente) ▹ Asíncrono ▸ Intercambio de información en tiempo diferido 14 Comunicación entre procesos 15 ” 16 Patrón Promesa ▹ Redirige flujos uniformes ▸ (A)sincronos ▹ Ordenada y estructura bloques ▸ then(myFunctionResolved(), myFunctionRejected()) ▹ Flexibiliza nuestro código ▸ CallBacks ▹ Hacer p(), y luego q(), r() y s() - [ p ⇒ q ⇒ r ⇒ s ] ▸ Promise(p).then(q).then(r).then(s); 17 Test-driven Development ( TDD ) ▹ Iteraciones ▸ Desarrollo mediante pruebas (Fallo - Acierto) ▸ Refactorizaciones ▹ Implementaciones mínimas necesarias ▹ Minimización del número de errores en producción ▹ Software modular, reutilizable y tolerable a cambios 18 ” 1. Object Oriented Programming Java 8, kotlin, scala, C#, C/C++, JavaScript ... 19 Java 8 Streams, Function Interface, Threading, CompletableFuture… 21 Java 8 - Emulador GameBoy DMG 01 / Homebrew ▹ ▹ ▹ ▹ ▹ ▹ Metodología SOLID + TDD Desarrollo de un Framework (Winter) CPU Z80 emulada con un Pool Asíncrono SRAM emulada para el Display LCD Backlights customizadas por colores Tooling ▸ Consola asíncrona para debug ▸ Decompilador de instrucciones Z80 ▸ Rom Hacking 22 Java 8 - Ejemplo de uso - Emulador GameBoy 23 Java 8 - Ejemplo de uso - Emulador GameBoy 24 Java 8 - Ejemplo de uso - Emulador GameBoy 25 Java 8 - Mejores Prácticas con Streams { Ejemplos } ▹ ▹ ▹ ▹ ▹ Clase que soporta operaciones con estilo funcional Lambdas Interfaces funcionales Métodos y constructores por referencias Definición de métodos predeterminados y estáticos a interfaces (Traits ?) ▹ Acceso mediante patrón “Builder” - Pipelines 26 Java 8 - Streams { allMatch } /** * Returns whether all elements of this stream match the provided predicate * @throws Exception */ @Test public void allMatch() throws Exception { final boolean result = IntStream.of(0, 1, 2, 3, 4, 5, 6) .allMatch(value -> value % 1 == 0); Assert.assertTrue(result); } 27 Java 8 - Streams { reduce } /** Performs a reduction on the elements of this stream, using an associative accumulation * function, and returns an Optional describing the reduced value, if any. * @throws Exception */ @Test public void reduce() throws Exception { final int expected = 789; final int result = Arrays.asList(18, 19, 29, 23, 43, 266, 789) .stream() .reduce((p1, p2) -> p1 > p2 ? p1 : p2) .get(); Assert.assertTrue(expected == result); } 28 Java 8 - Creando nuestra programación funcional ▹ Package java.utils.Functions ▸ Function <T,R>, BiFunction <T,U,R> ▸ Consumer <T>, BiConsumer <T,U> ▸ Predicate <T>, BiPredicate <T,U> ▸ Supplier <T> ▸ BinaryOperation <T> ▸ UnaryOperation <T> ▹ @Functional Interface 29 Java 8 - Creando nuestra programación funcional 1/2 /** * Expresión Lambda que suma un incremento de +1 * @throws Exception */ Function<Integer,Integer> add1 = x -> x + 1; @Test public void addTest() throws Exception { final int expected = 2; final int result = add1.apply(1); Assert.assertTrue(expected == result); } 30 Java 8 - Creando nuestra programación funcional 2/2 /** * Expresión Lambda que implementa la suma de un operador * @throws Exception */ BinaryOperation<Integer> sum = (x,y) -> x + y; @Test public void sumTest() throws Exception { final int expected = 4; final int result = sum.apply(1,3); Assert.assertTrue(expected == result); } 31 Java 8 - Migrando OOP a FP /** * Clase que suma un incremento de +2 * @throws Exception */ public class Utils { public static Integer add2(Integer x) { return x + 2; } } Function<Integer,Integer> add2 = Utils::add2; @Test public void addTest() throws Exception { final int expected = 4; final int result = add2.apply(2); Assert.assertTrue(expected == result); } 32 Java 8 - Functional Interface /** * Interface que checkea un enumerado de tipo checkeable * @throws Exception */ @FunctionalInterface public interface ICheck { Boolean check(Checkeable c); } @Test public void composeTest() throws Exception { final ICheck newChecker = c -> c.toString().equals("COMPLETED"); final boolean result = newChecker.check(CheckEnum.FINISHED); Assert.assertNotEquals(CheckEnum.COMPLETED, result); } 33 Java 8 - Ejemplo de uso - Scanlines Horizontal w/576i Emu GameBoy 34 Java 8 - Ejemplo de uso - Scanlines Horizontal w/576i Emu GameBoy 35 Java 8 - Ejemplo de uso - Scanlines Horizontal w/576i Emu GameBoy ▹ ▹ ▹ ▹ Proceso Concurrente Productor y Consumidor de Imágenes Recorrido, filtrado y reducciones con Streams Uso de variables ‘volatiles’ en contexto Threading 36 Java 8 - Programación Asíncrona ▹ ▹ ▹ ▹ ▹ Thread - Runnable Executors Callables - Futures Scheduled Executors CompletableFuture (Patrón Promesa) ▸ CompletableStage ▸ Future 37 Java 8 - Threads y Runnables final Runnable runnable = () -> { String threadName = Thread.currentThread().getName(); System.out.println("Hello " + threadName); }; final Thread thread = new Thread(runnable); thread.start(); System.out.println("Done!"); … eq new Thread(() -> { System.out.println("Hello " + Thread.currentThread().getName()) }).start(); System.out.println("Done!"); 38 Java 8 - Executors final ExecutorService executor = Executors.newSingleThreadExecutor(); executor.submit(() -> { String threadName = Thread.currentThread().getName(); System.out.println("Hello " + threadName); }); System.out.println("Done! "+executor.isTerminated()); 39 Java 8 - Callable y Futures final Callable<Integer> callable = () -> { int res = 0; try { TimeUnit.SECONDS.sleep(1); return 0; } catch (InterruptedException e) { res = -1; throw new IllegalStateException("task interrupted", e); } finally { return res; } }; final ExecutorService executor = Executors.newSingleThreadExecutor(); final Future future = executor.submit(callable); final int result = future.get(); // Esperamos a que se resuelva la promesa mientras procesamos otros flujos System.out.println("Done! "+executor.isTerminated()+" "+result); 40 Java 8 - Scheduled Executor final ScheduledExecutorService executor = Executors.newScheduledThreadPool(1); executor.scheduleWithFixedDelay(() -> { try { TimeUnit.SECONDS.sleep(2); System.out.println("Scheduling: " + System.nanoTime()); } catch (InterruptedException e) { System.err.println("task interrupted"); } finally { if(!executor.isTerminated() System.err.println("cancel no finished task"); executor.shutdownNow(); } }, 0, 1, TimeUnit.SECONDS); 41 Java 8 - CompetableFutures (LoadAsync Roms for Gb Emulator) public static CompletableFuture<ByteBuffer> read(String filePath, int total) final CompletableFuture<ByteBuffer> completableFuture = throws Exception { new CompletableFuture(); final AsynchronousFileChannel channel = AsynchronousFileChannel.open(Paths.get(filePath), StandardOpenOption.READ); final ByteBuffer buffer = ByteBuffer.allocate(total); channel.read(buffer, 0, null, new CompletionHandler<Integer, Void>() { @Override public void completed(Integer result, Void attachment) { try { channel.close(); } catch (IOException e) { e.printStackTrace(); } buffer.flip(); completableFuture.complete(buffer); } @Override public void failed(Throwable exc, Void attachment) { completableFuture.completeExceptionally(exc); } }); }); return completableFuture; } 42 Emulador GameBoy - DMG-01 ▹ Futuras issues ??? ▸ Servicio asíncrono para descargar Roms online ▸ Pintar Tiles 8x16 ▸ Emular sonido C# 44 C# - Ejemplo de uso - T-Rex Game Lovely 45 C# - Ejemplo de uso - T-Rex Game Lovely 46 C# - Ejemplo de uso ▹ Cube Line Match 3 Focus Node Selected** Auto Remove Link Match Line / Left outer join** ** Copia de SleepyWings 47 C# - Ejemplo de uso ‘Cube Line Match 3’ ▹ ▹ ▹ ▹ ▹ ▹ Arquitectura MVC + Adaptador Procesamiento Asíncrono con ‘Tasks’ Pool Threading Task Async Uso de Linq ‘Left Outer Join’ sobre LinkedList Resolución de Matchs por Recursión 48 Unitor - Micro Framework para Unity 2D/3D ▹ Metodología SOLID + TDD ▹ Arquitectura basada en los mejores Frameworks ▸ ▸ ▸ ▸ ▸ ▸ ▸ Contexto Injector Dispatcher Asíncrono CommandMappers Asíncrono Pre-Configuración de recursos Asíncronos Promesas ... 49 C# - Programación Funcional ▹ Delegados ▸ Func<in T, out T> ▸ Action<in T> ▸ Predicate<in T> ▹ Lambdas ▸ Compile-time duck typing (dynamic keyword) ▹ Linq Queries 50 C# - Func<in T… , out TResult> private static double Multiplicar(double num1, double num2) { return num1*num2; } public static void Main(string[] args) { double num1 = 18; double num2 = 36; Func<double, double, double> operacionMultipl = Multiplicar; Console.WriteLine(string.Format("Multiplicar: {0}", resultMultipl(num1,num2)); } 51 C# - Action<in T… , out Void> private static void Dividir(double num1, double num2) { double resultado = num1/num2; Console.WriteLine(string.Format("Division: {0}", resultado)); } public static void Main(string[] args) { double num1 = 8; double num2 = 6; Action<double, double> dividir = Dividir; dividir(num1, num2); } 52 C# - Predicate<in T… ,out Boolean> private static bool FindPoints(Point obj) { return obj.X * obj.Y > 100000; } public static void Main() { Point[] points = { new new new new new }; Point(100, Point(150, Point(250, Point(275, Point(295, 200), 250), 375), 395), 450) Point first = Array.Find(points, FindPoints); Point first = Array.Find(points, x => x.X * x.Y > 100000 ); Console.WriteLine("Found: X = {0}, Y = {1}", first.X, first.Y); } 53 C# - Lambda Expression public static void Main(string[] args ) { var first = Array.Find({ new Point(250, 375),new Point(275, 395), new Point(295, 450) }, point => point.X * point.Y > 100000 ); Console.WriteLine("Found: X = {0}, Y = {1}", first.X, first.Y); } public static void Main(string[] args) { var dividir = (x,y) => Console.WriteLine(string.Format("Division: {0}", x/y)); dividir(10,5); } public static void Main(string[] args) { var multiplicar = (x, y) => (x * y); Console.WriteLine(string.Format("Multiplicar: {0}", multiplicar(10,5)); } 54 C# - Linq Query - Where Indexer public static void Where_Indexer(string[] args ) { { var digits = new String[]{ "zero", "one", "two", "three", "four", "five", "six", "seven", "eight", "nine" }; digits.Where((digit, index) => digit.Length < index) .ToList() .ForEach(x => Console.WriteLine("The word {0} is shorter than its value.", x) ); } 55 C# - Linq Query - GroupBy public static void Where_Indexer(string[] args ) { var anagrams = new String[]{ "from ", " salt", " earn ", " last ", " near ", " form " }; var orderGroups = anagrams.GroupBy( w => w.Trim(), a => a.ToUpper(), new AnagramEqualityComparer()); ... } public class AnagramEqualityComparer : IEqualityComparer<string>{ public bool Equals(string x, string y) { return getCanonicalString(x) == getCanonicalString(y); } public int GetHashCode(string obj){ return getCanonicalString(obj).GetHashCode(); } private string getCanonicalString(string word) { char[] wordChars = word.ToCharArray(); Array.Sort<char>(wordChars); return new string(wordChars); } } 56 C# - Linq Query - TakeWhile public void TakeWhile_Indexer() { int[] numbers = { 5, 4, 1, 3, 9, 8, 6, 7, 2, 0 }; var firstNumbersLessThan6 = numbers.TakeWhile(n => n < 6); Console.WriteLine("First numbers less than 6:"); foreach (var n in firstNumbersLessThan6) { Console.WriteLine(n); } } -eq public static void TakeWhile_Indexer(string[] args ) { Console.WriteLine("First numbers less than 6:"); new[]{ 5, 4, 1, 3, 9, 8, 6, 7, 2, 0 }.TakeWhile(n => n < 6) .ToList() .ForEach(x => Console.WriteLine(x)); } 57 C# - Programación Asíncrona ▹ CLR v1: APM – Modelo de Programación Asíncrona ▹ CLR v2: EAP – Patrón Asíncrono basado en Eventos ▹ CLR v4: TAP – Patrón Asíncrono basado en Tareas ▸ V4.5 async/await ▸ V4.6 Métodos estáticos con async/await & bloques catch/finally ▹ C# v7 : Out vars, Pattern Matching, Arbitrary async returns 58 C# - Task & Modelo de Programación Asíncrona (APM) // Método que permite leer de manera asíncrona // un stream dado el buffer, offset y su contador // public static Task<int> ReadAsync(this Stream stream, byte [] buffer, int offset, int count) { if (stream == null) throw new ArgumentNullException(“stream = null”); var tcs = new TaskCompletionSource<int>(); stream.BeginRead(buffer, offset, count, iar => { try { tcs.TrySetResult( stream.EndRead(iar)); } catch(OperationCanceledException) { tcs.TrySetCanceled(); } catch(Exception exc) { tcs.TrySetException(exc); } }, null); return tcs.Task; } 59 C# - Task & Patrón Asíncronos basado en Eventos (EAP) // Método que permite descargar de manera asíncrona // una url // public static Task<string> DownloadStringAsync(Uri url) { var tcs = new TaskCompletionSource<string>(); var wc = new WebClient(); wc.DownloadStringCompleted += (s,e) => { if (e.Error != null) tcs.TrySetException(e.Error); else if (e.Cancelled) tcs.TrySetCanceled(); else tcs.TrySetResult(e.Result); }; wc.DownloadStringAsync(url); return tcs.Task; } EventHandler es ineficiente… Debemos usar Action<T> / Func<T,H> ... ▹ Async es un modificador que permite establecer o modificar la firma de un método formal, una expresión lambda, o un método anónimo para que sea tratado como un método asíncrono. ▹ await es un keyword que aplica a una tarea de un método asíncrono para suspender la ejecución del mismo hasta que la tarea en espera se resuelva. 60 ” Nota: Declarar un método como async es requisito indispensable para poder usar await. 61 C# - Mejores Prácticas con Task.Run<T> // Método que permite obtener de manera asíncrona // el tamaño en bytes de la página solicitada // private async Task<byte[]> SumPageSizesAsync() { HttpClient client = new HttpClient(); Task<byte[]> getContentsTask = client.GetByteArrayAsync(url); return getContentsTask; } var result = await SumPageSizesAsync(); ..eq byte[] result = await SumPageSizesAsync(); C# - Mejores Prácticas con Task.FromResult<T> 62 // Método que permite obtener de manera asíncrona // un número aleatorio o un tipo de dato resultado // public Task<int> GetValueAsync(int cachedValue) { return Task.Run(() => { System.Threading.Thread.Sleep(5000); return (TryGetValueAsync(out cachedValue) ? GetValueRamdonAsync() : Task.FromResult(cachedValue)); }); } public Boolean TryGetValueAsync(out String value){ … } public async Task<int> GetValueRamdonAsync(int value){ … } 63 C# - Mejores Prácticas con Task - Retry or Fault // Método que permite de manera asíncrona // hacer la llamada a una funcion, con un número // de intentos y con una función de reintentos para su ejecución public static async Task<T> RetryOnFault(Func<Task<T>> function, int maxTries, Func<Task> retryWhen) { for (int i = 0; i < maxTries; i++) { try { return await function(); } catch { if(i== maxTries-1) throws … ; } await retryWhen.ConfigureAwait(false); } return default(T) } 64 Unitor - Micro Framework para Unity 2D/3D ▹ Futuras issues ??? ▸ Open source próximamente! C/C++ 66 + C/C++ - Space Invader Nintendo DS ▹ ▹ ▹ ▹ Compilador "devkitPro 1.5.0 ARM" no oficial Librería Libnds para la gestión del proyecto Librería Libfat-nds para el manejo de ficheros Librería MaxMod para el sonido 67 C/C++ - Space Invader Nintendo DS 68 C/C++ - Programación funcional ▹ Lambdas ▸ Compile-time duck typing ▹ std::function ▸ Programación funcional abstracta ▸ Run-time duck typing 69 C/C++ - Estructura Lambdas [closures] (params) -> ret {body} ▹ Closures entre corchetes [] ▹ Parámetros (si los hay) entre paréntesis () ▹ El tipo de retorno precedido por -> ▹ El cuerpo de la función entre corchetes {} 70 C/C++ - Closures Lambdas ▹ ▹ ▹ ▹ ▹ [] Tipo void, no encapsula nada [&] Variables capturadas por referencia [=] Variables capturadas por valor [this] Acceso a los miembros de un objeto [x=y] Captura con renombrado (C++14) 71 C/C++ - Lambdas #include <iostream> using namespace std; class Foo { public : Foo () : _x( 12345 ) {} void apply_x(const vector<int>& v)const { for_each(v.begin(),v.end(),[this](int n){cout<< n*_x <<endl;}); } void func () { [this] () { cout << _x; } (); } private : int _x; }; int main() { auto print = [] () { cout << "Hello world"; }; auto print2 = [] () { return 1; } //Infiere la salida el compilador auto print3 = [] () -> int { return 1; } // Imponemos el tipo de salida print(); print2(); print3(); Foo f; f.func(); } 72 C/C++ - std::function #include <iostream> #include <functional> using namespace std; void global_f() { cout << "global_f()" << endl; } struct Functor { void operator()() { cout << "Functor" << endl; } }; int main() { std::function<void()> foo; cout << "sizeof(f) == " << sizeof(f) << endl; foo = global_f; foo(); foo = [](){ cout << "Lambda" << endl;}; foo(); Functor functor; foo= functor; foo(); } 73 C/C++ - Programación concurrente con ppltask.h ▹ Concurrency::task ▸ ▸ ▸ ▸ Encadena múltiples operaciones sincrónicas y asincrónicas Administra excepciones Realizar cancelaciones Garantizar que las tareas individuales se ejecuten en el contexto o contenedor de subproceso apropiado 74 C/C++ - Consumiendo Op Async con Tareas #include <ppltasks.h> using namespace concurrency; using namespace Windows::Devices::Enumeration; void App::TestAsync() { IAsyncOperation<DeviceInformationCollection^>^ deviceOp = DeviceInformation::FindAllAsync(); auto deviceEnumTask = create_task(deviceOp); deviceEnumTask.then( [this] (DeviceInformationCollection^ devices ) { for(int i = 0; i < devices->Size; i++) DeviceInformation^ di = devices->GetAt(i); }); ... } 75 C/C++ - Encadenamiento de Op Async con Tareas #include <ppltasks.h> using namespace concurrency; using namespace Windows::Storage; void App::DeleteWithTasks(String^ fileName) { StorageFolder^ localFolder = ApplicationData::Current::LocalFolder; auto getFileTask = create_task(localFolder->GetFileAsync(fileName)); getFileTask .then([](StorageFile^ storageFileSample) ->IAsyncAction^ { return storageFileSample->DeleteAsync(); }) .then([](void) { OutputDebugString(L"File deleted."); }); } 76 C/C++ - Cancelación de Tareas #include <ppltasks.h> using namespace concurrency; using namespace Windows::Storage; void App::DeleteWithTasks(String^ fileName) { cancellation_token_source m_fileTaskTokenSource; StorageFolder^ localFolder = ApplicationData::Current::LocalFolder; auto getFileTask = create_task(localFolder->GetFileAsync(fileName), m_fileTaskTokenSource.get_token() ); getFileTask .then([](StorageFile^ storageFileSample) ->IAsyncAction^ { m_fileTaskTokenSource.cancel(); return storageFileSample->DeleteAsync(); }) .then([](void) { OutputDebugString(L"File deleted."); }); -> este bloque ya no se ejecutará xq hemos cancelado la tarea 77 C/C++ - Control de Errores con Tareas #include <ppltasks.h> using namespace Windows::Storage; using namespace concurrency; void App::DeleteWithTasksHandleErrors(String^ fileName) { StorageFolder^ documentsFolder = KnownFolders::DocumentsLibrary; auto getFileTask = create_task(documentsFolder->GetFileAsync(fileName)); getFileTask.then([](StorageFile^ storageFileSample) { return storageFileSample->DeleteAsync(); }) .then([](task<void> t) { try { t.get(); OutputDebugString(L"File deleted."); } catch (Platform::COMException^ e) { OutputDebugString(e->Message->Data()); } }); } 78 C/C++ - Calling Haskell / Cpphs #include <HsFFI.h> #ifdef __GLASGOW_HASKELL__ #include "Safe_stub.h" extern void __stginit_Safe(void); #endif #include <stdio.h> int main(int argc, char *argv[]) { int i; hs_init(&argc, &argv); #ifdef __GLASGOW_HASKELL__ hs_add_root(__stginit_Safe); #endif i = fibonacci_hs(42); printf("Fibonacci: %d\n", i); hs_exit(); return 0; } {-# LANGUAGE ForeignFunctionInterface #-} module Safe where import Foreign.C.Types fibonacci :: Int -> Int fibonacci n = fibs !! n where fibs = 0 : 1 : zipWith (+) fibs (tail fibs) fibonacci_hs :: CInt -> CInt fibonacci_hs = fromIntegral . fibonacci . fromIntegral foreign export ccall fibonacci_hs :: CInt -> CInt Otros lenguajes OOP 80 JavaScript - Programación Asíncrona ▹ ▹ ▹ ▹ Callbacks - Async Module Promises (2012) - Promises/A+ Generators / Yield (2015) - Hapi Async / await (2015) - Koa 81 JavaScript - Ejempo de uso Intro Street Fighter 1 <- Código + Assets 82 JavaScript - Ejempo de uso Intro Street Fighter 1 ▹ Promesa nativas de JS ▹ Timer Task ▹ Tweens 83 Scala y Kotlin - Programación Asíncrona ▹ ▹ ▹ ▹ Threads Futures Async/await Coroutines 84 Kotlin - Kotlin Koans 85 Scala - Programming in Scala First Edition 2. Functional Programming Haskell, Python, F#, ... 86 Haskell 88 ” 89 Haskell ▹ ▹ ▹ ▹ ▹ ▹ ▹ Lazy Evaluation Pattern Matching Type classes Funciones de primer orden Monads Recursividad Modules 90 Haskell - Programación asíncrona ▹ Control.Concurrent.Async 2.1.0 ▸ Spawning con automatic cancellation ▸ Querying Async ▸ STM operations ▸ Waiting for multiple Async ▸ Linking 91 Haskell - Combine Task import Control.Concurrent (threadDelay) test1 :: Task Int test1 = task1 $ do threadDelay 500000 putStrLn "Hello," return 1 combineTask :: Task Int combineTask = do n1 <- test1 n2 <- test2 return (n1 + n2) main = do fut <- fork combineTask n <- fut print n test2 :: Task Int test2 = task2$ do threadDelay 500000 putStrLn " world!" return 2 92 Haskell - Async wait import Control.Concurrent.Async … main = defaultMain tests tests = [ testCase "asyncWait" asyncWait ] value = 42 :: Int data TestException = TestException deriving (Eq,Show,Typeable) instance Exception TestException asyncWait :: Assertion asyncWait = do a <- async (return value) r <- wait a assertEqual "async_wait" r value 93 Haskell - Async poll import Control.Concurrent.Async … main = defaultMain tests tests = [ testCase "asyncPoll" asyncPoll ] value = 42 :: Int data TestException = TestException deriving (Eq,Show,Typeable) instance Exception TestException asyncPoll :: Assertion asyncPoll = do a <- async (threadDelay 500000) r <- poll a when (isJust r) $ assertFailure "" r <- poll a when (isJust r) $ assertFailure "" F# 95 F# ▹ ▹ ▹ ▹ ▹ ▹ ▹ Declaración Imperativa Lazy Evaluation a través de keyword (lazy) Pattern Matching Quoted Expression Funciones de primer orden Interoperabilidad con .Net Recursividad (Tail) 96 F# - Programación asincrona ▹ Clásico ▸ Thread, AutoResetEvent, BackgroundWorker y IAsyncResult ▹ Asynchronous workflows ▸ Async ▸ Async.RunSynchronously ▸ Async.Parallel 97 F# - AutoResetEvent open System let userTimerWithCallback = let event = new System.Threading.AutoResetEvent(false) let timer = new System.Timers.Timer(2000.0) timer.Elapsed.Add (fun _ -> event.Set() | > ignore ) printfn "Esperando : %O" DateTime.Now.TimeOfDay timer.Start() printfn "Haciendo cosas mientras esperamos al evento" event.WaitOne() | > ignore printfn "Timer ticked %O" DateTime.Now.TimeOfDay 98 F# - IAsync Result let fileWriteWithAsync = use stream = new System.IO.FileStream("test.txt", System.IO.FileMode.Create) printfn "Empezando escritura asincrona" let asyncResult = stream.BeginWrite(Array.empty,0,0,null,null) let async = Async.AwaitIAsyncResult(asyncResult) |> Async.Ignore printfn "Haciendo cosas mientras esperamos al evento" Async.RunSynchronously async printfn "Escritura asíncrona completada" 99 F# - Async.RunSynchronously let sleepWorkflow = async{ printfn "Empezamos a dormir el workflow %O" DateTime.Now.TimeOfDay do! Async.Sleep 2000 printfn "workflow finalizado %O" DateTime.Now.TimeOfDay } Async.RunSynchronously sleepWorkflow 100 F# - Async.Parallel let sleepWorkflowMs ms = async { printfn "%i ms workflow started" ms do! Async.Sleep ms printfn "%i ms workflow finished" ms } let sleep1 = sleepWorkflowMs 1000 let sleep2 = sleepWorkflowMs 2000 #time [sleep1; sleep2] |> Async.Parallel |> Async.RunSynchronously #time Conclusiones 101 102 Beneficios aportados por la programación asíncrona ▹ ▹ ▹ ▹ ▹ ▹ Explotamos rendimiento de procesador/es Evitamos cuellos de botella, bloqueos... Procesamiento de tareas en paralelo Trabajamos con subprocesos en interfaces de usuario Soporte a sistemas de alta escabilidad Robustez en las aplicaciones/juegos desarrollados 103 Desventajas de la programación asíncrona ▹ Código desarrollado ▸ Entendimiento ▸ Acoplamiento ▸ Mantenibilidad ▸ Dificultad de debuggear 104 Beneficios de la programación funcional ▹ ▹ ▹ ▹ ▹ Minimización del código Basado en expresiones Cálculos lambda Recursión Eficiencia 105 ” Preguntas / Sugerencias ??? 106 Referencias 107 108 Referencias ▹ ▹ ▹ ▹ ▹ ▹ ▹ ▹ https://github.com/vicboma1/Java8-Stream https://www.todojs.com/programacion-asincrona-paso-de-continuadores-eventos-pro mesas-y-generadores/ http://itpn.mx/recursosisc/4semestre/topicosavanzados/Unidad%20IV.pdf http://elmanantialdebits.blogspot.com.es/2013/08/que-es-eso-de-la-programacion-asi ncrona.html http://concurrenteparalela.blogspot.com.es/2012/11/caracteristicas-programacion.ht ml http://www.depi.itchihuahua.edu.mx/apacheco/lengs/paralelo/index.html http://www.johndcook.com/blog/2010/11/03/object-oriented-vs-functional-programmi ng https://msdn.microsoft.com/en-us/magazine/jj991977.aspx?tduid=(a46d0d465c0b3794 7c4a3901d32004e2)(256380)(2459594)(TnL5HPStwNw-mIXzBM2g9PT4zCIuyzsidQ)() 109 Referencias ▹ ▹ ▹ ▹ ▹ ▹ ▹ ▹ ▹ https://dzone.com/articles/functional-programming-java-8 http://www.drdobbs.com/jvm/lambda-expressions-in-java-8/240166764 http://winterbe.com/posts/2015/04/07/java8-concurrency-tutorial-thread-executor-exa mples/ http://zeroturnaround.com/rebellabs/why-the-debate-on-object-oriented-vs-functiona l-programming-is-all-about-composition/ https://msdn.microsoft.com/es-es/library/mt674882.aspx http://es.slideshare.net/JeffHart6/async-await-46060988 https://msdn.microsoft.com/es-es/library/jj130730.aspx https://www.microsoft.com/en-us/download/confirmation.aspx?id=19957 http://stackoverflow.com/questions/7627098/what-is-a-lambda-expression-in-c11 110 Referencias ▹ ▹ ▹ ▹ ▹ ▹ ▹ ▹ ▹ ▹ https://msdn.microsoft.com/es-es/windows/uwp/threading-async/asynchronous-progr amming-in-cpp-universal-windows-platform-apps https://blog.risingstack.com/introduction-to-koa-generators/ https://www.npmjs.com/package/async https://github.com/promises-aplus https://github.com/vicboma1/C-Sharp-Promise https://msdn.microsoft.com/es-es/library/bb397687.aspx http://www.adobe.com/support/documentation/en/flex/1/mixin/mixin2.html#118542 http://slides.com/juanramb/promesas-en-javascrip https://usingstdcpp.files.wordpress.com/2014/12/introduccic3b3n-a-la-programacic3b 3n-funcional-en-c.pdf https://gobyexample.com 111 Java 8 - Rom Hacking <- Video