solution with higer-order function