Share to: share facebook share twitter share wa share telegram print page

Fonction de rappel

En informatique, une fonction de rappel (callback en anglais) ou fonction de post-traitement est une fonction qui est passée en argument à une autre fonction. Cette dernière peut alors faire usage de cette fonction de rappel comme de n'importe quelle autre fonction, alors qu'elle ne la connaît pas par avance.

Principe

La technique de la fonction de rappel s'inspire du principe d'Hollywood (ou Inversion de contrôle) où l'appelant laisse ses coordonnées pour pouvoir être rappelé par la suite. L'intérêt est le passage à un modèle événementiel et modulaire.

Illustration

Prenons l'exemple d'un programme contenant une partie Analyseur effectuant par exemple l'analyse lexicale d'un document. Supposons qu'une partie Traitement du programme, soit capable de compter les occurrences des mots qui lui sont transmis. Si Traitement se déclare en attente d'événements émanant d'Analyseur pour chaque mot reconnu au moyen d'une fonction de rappel, alors le programme global permettra de compter les occurrences des mots du texte analysé. Or, la partie Analyseur ne gère pas spécifiquement le comptage des mots et ne dépend pas de Traitement. Elle peut donc être réutilisée pour une autre tâche comme le test de la présence de mots-clés.

Pseudo-code de l'Analyseur :

// Variable de type fonction stockant la fonction de rappel
fonction(mot) traiterMot;

// Affectation de la fonction de rappel
fixerFonctionTraitementMot(fonction(mot) f) {
  traiterMot <- f;
}

// Corps de l'analyseur
analyse() {
  ...
  traiterMot(mot);
  ...
}

Pseudo-code du Traitement :

// Définition de la fonction qui sera rappelée
nouvelleOccurrence(mot) {
  ...
}
 

Pseudo-code du programme principal :

// préparation du rappel et 
fixerFonctionTraitementMot(nouvelleOccurrence);

//appel de l'analyseur
analyse();

Exemple

Dans un tableau de nombres, nous recherchons le premier entier supérieur strictement à 5 parmi les 5 premiers éléments du tableau. (en langage C).


La première approche sans fonction de rappel :

  int i;
  int length = 5;
 
 for (i = 0; i < length; i++)
 {
     if (array[i] > 5) 
     { 
         printf("Item %d\n", i);
         break;
     }
 }
 
 if (i == length) 
 {
     printf("Not found\n");
 }

La seconde avec fonction de rappel :

 /* LIBRARY CODE */
 int traverseWith(int array[], size_t length, 
                  int (*callback)(int index, int item, void *param), 
                  void *param)
 {
     int exitCode = 0;
     for (int i = 0; i < length; i++) {
         exitCode = callback(i, array[i], param);
         if (exitCode != 0) { 
             break;
         }
     }
     return exitCode;
 }
  
 /* APPLICATION CODE */
 int search (int index, int item, void *param)
 {
     if (item > 5) {
         *(int *)param = index;
         return 1;
     } else {
         return 0;
     }
 }
 
 /* (in another function) */
 int index;
 int found;
 found = traverseWith(array, length, &search, &index);
 if (found) {
     printf("Item %d\n", index);
 } else {
     printf("Not found\n");
 }

Mise en œuvre par passage de fonctions en paramètre

Les fonctions de rappel ont été très utilisées en programmation système et notamment en langage C. En effet, le C a permis assez tôt de passer des pointeurs de fonctions en paramètre d'autres fonctions. Cela le rendait techniquement capable d'implémenter le mécanisme des fonctions de rappel.

Le passage de fonction en paramètre est généralisé en programmation fonctionnelle. Toutefois dans ce cadre, on ne parle plus de fonction de rappel. Dans ce paradigme, les fonctions sont des éléments de première classe (au même titre que les constantes par exemple). Aussi, les fonctions qui peuvent prendre d'autres fonctions en argument et/ou renvoyer une fonction comme valeur de retour sont alors qualifiées de fonctions d'ordre supérieur.

Évolution du principe

Avec l'apparition de la programmation objet et des interfaces, la technique de rappel a évolué. On passe maintenant en paramètre un objet qui se conforme à une interface donnée. Il n'y a donc plus une, mais autant de fonctions que l'on souhaite rappeler. De plus le fait de passer un objet permet de contextualiser en indiquant sur quoi s'effectue le rappel, tandis qu'une fonction de rappel précisait seulement comment rappeler. Cependant la technique des fonctions de rappel continue à avoir les faveurs des langages disposant de fermetures, où celles-ci offrent des capacités équivalentes aux objets en termes de contexte.

Voir aussi

Read more information:

Seri Dragon BallGambar sampul Cell Mencapai Wujud Sempurna.MangaAlbum nomor32EpisodeCell SagaDidahului olehCell MengancamDiikuti denganPermainan Cell DimulaiDiterbitkan di Jepang1984Diterbitkan di Indonesia1994 Cell Mencapai Wujud Sempurna adalah jilid ke-32 manga Dragon Ball. Pada jilid ini, diceritakan bagaimana Cell yang merupakan makhluk aneh berwarna hijau dan bisa menghisap tenaga makhluk hidup berusaha mencapai wujud sempurna. Cell berusaha mencari manusia-manusia buatan Dr. Gero lainnya …

اشتباكات جنوب لبنان في سبتمبر 1992جزء من الصراع في جنوب لبنان (1982-2000)التاريخ30 سبتمبر 1992الموقعجنوب لبنانالنتيجةصد هجوم حزب الله على موقع جيش لبنان الجنوبيالمتحاربونجيش لبنان الجنوبي حزب اللهالإصابات والخسائر9 قتلى، من بينهم فرد من حفظة السلام التابعين لليونيفيل عنتصندوق الص…

أندريوس كوبيليوس (بالليتوانية: Andrius Kubilius)‏  معلومات شخصية الميلاد 8 ديسمبر 1956 (العمر 66 سنة)فيلنيوس  مواطنة الاتحاد السوفيتي ليتوانيا  مناصب عضو برلمان   في المنصب25 نوفمبر 1992  – 14 نوفمبر 2004  رئيس وزراء ليتوانيا   في المنصب3 نوفمبر 1999  – 26 أكتوبر 2000  رولاند

American professional wrestler and mixed martial arts (MMA) fighter For the baseball player, see Jake Hager (baseball). Jake HagerHager in April 2014Birth nameDonald Jacob Hager Jr.Born (1982-03-24) March 24, 1982 (age 41)[1]Fargo, North Dakota, U.S.[2]Alma materUniversity of OklahomaSpouse(s) Catalina White ​(m. 2010)​Children2Professional wrestling careerRing name(s)Jack SwaggerJake Hager[3]Jake StrongBilled height6 ft 7 in (2…

لويس إرنستو بيريز معلومات شخصية الميلاد 12 يناير 1981 (العمر 42 سنة)مدينة مكسيكو الطول 1.71 م (5 قدم 7 1⁄2 بوصة) مركز اللعب وسط الجنسية المكسيك  معلومات النادي النادي الحالي المكسيك تحت 20 (مدرب) المسيرة الاحترافية1 سنوات فريق م. (هـ.) 1999–2003 نيكاكسا 114 (13) 2003–2012 مونتيري 323 (…

M. et A. Dulac Rechtsform Gründung 1899 Auflösung 1901 Sitz Paris, Frankreich Branche Automobilindustrie Dulac 4,5 CV De Dion-Bouton (1899) Dulac 4,5 CV De Dion-Bouton (1899) M. et A. Dulac war ein französischer Hersteller von Automobilen.[1][2][3] Inhaltsverzeichnis 1 Unternehmensgeschichte 2 Fahrzeuge 3 Literatur 4 Weblinks 5 Einzelnachweise Unternehmensgeschichte Das Unternehmen aus Paris begann 1899 mit der Produktion von Automobilen. Der Markenname lautete in Fran…

2012 single by Tyga FadedSingle by Tyga featuring Lil Waynefrom the album Careless World: Rise of the Last King ReleasedJanuary 13, 2012 (2012-01-13)Recorded2011GenreHip hopLength3:33Label Young Money Cash Money Republic Songwriter(s)Michael Stevenson, Dwayne Carter, Diome SilvaProducer(s)Dnyc3, Cisse MethodsTyga singles chronology Rack City (2011) Faded (2012) Ayy Ladies (2012) Lil Wayne singles chronology The Motto(2011) Faded(2012) All Aboard(2012) Faded is a song by Am…

American RiverAmerican River at the Jedediah Memorial Trail BridgeLocationSacramento, California The Hodge decision is a flow requirement that several water agencies must follow when they extract surface water from the American River. The flow requirements vary throughout the year, with the spring and summer months of March through June presenting the most restricted rate, at a minimum of 3,000 cubic feet per second (85 m3/s). The agencies must maintain these specified flow rates to divert …

County in West Virginia, United States For other uses, see Wyoming County (disambiguation). County in West VirginiaWyoming CountyCountyWyoming County Courthouse and Jail in Pineville SealLocation within the U.S. state of West VirginiaWest Virginia's location within the U.S.Coordinates: 37°37′N 81°32′W / 37.61°N 81.54°W / 37.61; -81.54Country United StatesState West VirginiaFoundedJanuary 26, 1850SeatPinevilleLargest cityMullensArea • Total502…

Jari Kainulainen Jari Kainulainen, Nosturi 2008Información personalNacimiento 29 de abril de 1970 en Helsinki, Finlandia) Helsinki (Finlandia) Nacionalidad FinlandesaInformación profesionalOcupación BajistaAños activo 1992 - presenteGénero Power metal Speed metalInstrumento Guitarra bajo y guitarra Artistas relacionados Stratovarius Kotipelto Evergrey Mess MasterplanMiembro de MasterplanStratovariusKotipeltoEvergrey Sitio web www.myspace.com/jarikainulainen[editar datos en Wikidata…

Keishu Tanaka田中 慶秋Menteri KeadilanMasa jabatan1 Oktober 2012 – 24 Oktober 2012Perdana MenteriYoshihiko NodaPendahuluMakoto TakiPenggantiMakoto Taki Informasi pribadiLahir(1938-03-06)6 Maret 1938Sōma, JepangMeninggal4 Januari 2022(2022-01-04) (umur 83)Partai politikPartai DemokratikAlma materUniversitas TokaiSunting kotak info • L • B Keishu Tanaka (田中 慶秋code: ja is deprecated , Tanaka Keishū); 6 Maret 1938 – 4 Januari 2022) adalah s…

Neraka Joseon digambarkan dengan peta seluruh Semenanjung Korea yang diwarnai dengan warna api neraka. Neraka Joseon, Neraka Chosun atau Neraka Korea (bahasa Korea: 헬조선) adalah istilah sindiran Korea yang mencela kondisi sosio-ekonomi Korea sekarang ini.[1] Istilah ini populer terutamanya dengan generasi muda Korea, yang mana kekhawatiran utama mereka berkaitan dengan pengangguran dan kondisi pekerjaan (termasuk perlakuan kasar kepada karyawan yang disebabkan tradisi Konfusiani…

Фране Матошич Особисті дані Народження 25 листопада 1918(1918-11-25)   Спліт, Держава Словенців, Хорватів і Сербів Смерть 29 жовтня 2007(2007-10-29) (88 років)   Спліт, Хорватія Поховання Ловринацd[1] Громадянство  Югославія Позиція нападник Професіональні клуби* Роки Клуб І (г) 1…

Mountain in Nepal KumbhakarnaJannuJannu from the southHighest pointElevation7,710 m (25,300 ft)[1]Ranked 32ndProminence1,035 m (3,396 ft)ListingList of mountains in NepalCoordinates27°40′58″N 88°02′45″E / 27.68278°N 88.04583°E / 27.68278; 88.04583GeographyKumbhakarnaLocation in Nepal LocationEastern NepalParent rangeHimalayasClimbingFirst ascentApril 27–28, 1962 by René Desmaison, Paul Keller, Robert Paragot, Gyalzen Mitchun…

Acesso à estação. Plataformas de embarque. Europa | Fira é uma estação da linha Linha 8 e Linha 9 do Metro de Barcelona, atendendo também as linhas S3, S4, S8, S9, R5, R6, R50 e R60 da linha FGC Llobregat-Anoia localizada abaixo da Plaza Europa na Gran Vía em Hospitalet de Llobregat. A estação foi inaugurada em Maio de 2007, entre as estações Ildefons Cerdà e Gornal e foi ampliada para se conectar com a linha 9 do TMB. Os acessos são pela Gran Vía de Hospitalet de Llobregat, com a…

Length in a vector space This article is about norms of normed vector spaces. For field theory, see Field norm. For ideals, see Ideal norm. For group theory, see Norm (group). For norms in descriptive set theory, see prewellordering. In mathematics, a norm is a function from a real or complex vector space to the non-negative real numbers that behaves in certain ways like the distance from the origin: it commutes with scaling, obeys a form of the triangle inequality, and is zero only at the origi…

District in Turrialba canton, Cartago province, Costa Rica District in Cartago, Costa RicaSanta CruzDistrictSanta Cruz districtSanta CruzSanta Cruz district location in Costa RicaCoordinates: 10°00′37″N 83°45′16″W / 10.0103262°N 83.7545832°W / 10.0103262; -83.7545832Country Costa RicaProvinceCartagoCantonTurrialbaCreation14 February 1920Area • Total124.94 km2 (48.24 sq mi)Elevation1,475 m (4,839 ft)Population (201…

Dutch girl group This article does not cite any sources. Please help improve this article by adding citations to reliable sources. Unsourced material may be challenged and removed.Find sources: Frizzle Sizzle – news · newspapers · books · scholar · JSTOR (October 2008) (Learn how and when to remove this template message) Frizzle Sizzle were a Dutch teenage girl group of the 1980s. The four members of the group were Karin Vlasblom (born 10 August 1967), La…

Football video game This article is about the video game. For the tournament, see 2022 FIFA World Cup. 2021 video gameEA Sports FIFA 22Current Gen Standard cover art featuring Paris Saint-Germain and France player Kylian MbappéDeveloper(s)EA VancouverEA RomaniaPublisher(s)EA SportsSeriesFIFAEngineFrostbite 3Platform(s)Nintendo SwitchPlayStation 4PlayStation 5StadiaWindowsXbox One Xbox Series X/SRelease1 October 2021Genre(s)SportsMode(s)Single-player, multiplayer FIFA 22 is a football simulation…

Artikel ini tidak memiliki referensi atau sumber tepercaya sehingga isinya tidak bisa dipastikan. Tolong bantu perbaiki artikel ini dengan menambahkan referensi yang layak. Tulisan tanpa sumber dapat dipertanyakan dan dihapus sewaktu-waktu.Cari sumber: Sejarah Jawa Timur – berita · surat kabar · buku · cendekiawan · JSTOR Artikel ini perlu diwikifikasi agar memenuhi standar kualitas Wikipedia. Anda dapat memberikan bantuan berupa penambahan pranala dalam,…

Canterbury Earthquake National Memorial The Canterbury Earthquake National Memorial (Māori: Oi Manawa[1]) is the Crown's official memorial for those killed or seriously injured in the 22 February 2011 Christchurch earthquake. It is located on both sides of the Avon River downstream from the Montreal Street bridge. The memorial opened on 22 February 2017, the sixth anniversary of the earthquake. Project development Memorial site The memorial was one of the projects identified in the Chri…

2005 film The ViolinFilm posterDirected byFrancisco VargasWritten byFrancisco VargasProduced byÁngeles CastroHugo RodríguezStarringÁngel TaviraCinematographyMartín BoegeEdited byRicardo GarfiasDistributed byCanana Films[1]Release date 11 March 2005 (2005-03-11) Running time98 minutesCountryMexicoLanguageSpanish The Violin (Spanish: El violín) is a 2005 Mexican drama film directed by Francisco Vargas. It was screened in the Un Certain Regard section at the 2006 Cannes …

Batalla de Járkov Parte de la ofensiva de Ucrania oriental (invasión rusa de Ucrania) Calle del centro de Járkov afectado por los combates. Situación de Járkov (en: Kharkiv en el mapa) durante la batalla.Fecha 24 de febrero–14 de mayo (2 meses y 18 días)Lugar Járkov, Óblast de Járkov Coordenadas 49°59′33″N 36°13′52″E / 49.9925, 36.231111111111Resultado Victoria ucraniana Ucrania repele la ofensiva rusa del extrarradio de Járkov hasta la frontera no…

This article is about the former French department. For the city known as Gênes in French, see Genoa. Département de Gênesdepartment of the First French Empire1805–1815 FlagAdministrative map of the Italian portion of the French Empire.CapitalGenoaArea • Coordinates44°24′N 8°55′E / 44.400°N 8.917°E / 44.400; 8.917  • 1812[1]2,376 km2 (917 sq mi)Population • 1812[1] 400056 HistoryHistory …

Не плутати з J-PARC. PARCангл. PARC Логотип Тип бізнесГалузь R&DЗасновано 1970Штаб-квартира Пало-АльтоХолдингова компанія Xeroxparc.com  PARC у Вікісховищі Xerox Alto — перший у світі комп'ютер з графічним інтерфейсом, розробленний в Xerox PARC PARC (англ. Palo Alto Research Center), раніше Xerox PARC — науков…

German footballer Jean Zimmer Zimmer training with VfB Stuttgart in 2016Personal informationDate of birth (1993-12-06) 6 December 1993 (age 30)Place of birth Bad Dürkheim, GermanyHeight 1.71 m (5 ft 7 in)Position(s) Right-backTeam informationCurrent team 1. FC KaiserslauternNumber 8Youth career2010–2012 1. FC KaiserslauternSenior career*Years Team Apps (Gls)2012–2014 1. FC Kaiserslautern II 59 (1)2013–2016 1. FC Kaiserslautern 61 (5)2016–2018 VfB Stuttgart 16 (0)2016…

Bride of the CenturyPoster promosi untuk Bride of the CenturyGenreKomedi Roman Fantasi MelodramaDitulis olehBaek Young-sookSutradaraYoon Sang-hoPemeranLee Hong-gi Yang Jin-sung Sung HyukNegara asalKorea SelatanBahasa asliKoreaJmlh. episode16ProduksiProduser eksekutifChoi Byung-hwaProduserJung Hyung-seo Jung Hoe-seokLokasi produksiKoreaRumah produksiAura MediaRilis asliJaringanTV ChosunRilis22 Februari (2014-02-22) –12 April 2014 (2014-4-12) Bride of the Century (Hangul: …

Cet article est une ébauche concernant le jeu vidéo. Vous pouvez partager vos connaissances en l’améliorant (comment ?) (voir l’aide à la rédaction). Si ce bandeau n'est plus pertinent, retirez-le. Cliquez ici pour en savoir plus. Cet article ne cite pas suffisamment ses sources (mai 2017). Si vous disposez d'ouvrages ou d'articles de référence ou si vous connaissez des sites web de qualité traitant du thème abordé ici, merci de compléter l'article en donnant les références…

Pour les articles homonymes, voir Symons. Cet article est une ébauche concernant un militaire britannique. Vous pouvez partager vos connaissances en l’améliorant (comment ?) selon les recommandations des projets correspondants. William Penn SymonsBiographieNaissance 17 juillet 1843Hatt (en)Décès 23 octobre 1899 (à 56 ans)Dundee (Afrique du Sud)Nationalité britanniqueFormation Collège royal militaire de SandhurstActivité MilitaireAutres informationsArme British ArmyGrade milit…

Obras de Antoni Gaudí ★ Património Mundial da UNESCO Sagrada Família Critérios C(i) C(ii) C(vi) País Espanha Coordenadas Parque Güell: Carrer d'Olot 41º24'49N 2º09'11E Palácio Güell: Carrer Nou de La Rambla, 3-5 41º22'45N 2º10'28E Casa Milà: Passeig de Gràcia, 92 41º23'43N 2º09'43E Casa Vicens: Carrer de los Carolines, 22 41º24'13N 2º09'04E Sagrada Família Plaça de la Sagrada Familia 41º24'12N 2º10'27E Casa Batlló Passeig de Gràcia, 43 41º23'30N 2º09'54E Cripta d…

Kembali kehalaman sebelumnya

Lokasi Pengunjung: 18.191.132.194