Write a tail recursive version of the map function
Réponses aux questions d'entretien
Utilisateur anonyme
17 sept. 2012
let map f l =
let rec map' f l x =
match l with
|[] -> x []
|hd::tl -> map' f tl (fun lst -> x ((f hd)::lst))
in
map' f l (fun lst -> lst)
;;
2
Utilisateur anonyme
16 juin 2014
The previous answer seems a bit too complex, i would rewrite it as :
let rec mytailmap f m =
let rec aux f m result =
match m with
| [] -> result
| h::t -> aux f t (result@[(f h)])
in aux f m [] ;;
val mytailmap : ('a -> 'b) -> 'a list -> 'b list =
2
Utilisateur anonyme
6 sept. 2018
```
tailMap :: (a->b) -> ([b]->[b]) -> [a] -> [b]
tailMap _ _ [] = []
tailMap f k (x:[]) = k [f x]
tailMap f k (x:xs) = tailMap f (\r -> k $ ((f x) : r)) xs
```