functional KMP algorithm