Worms learn how to optimize foraging by switching their resp