房子

房子

中等

說明

背誦童謠「This is the House that Jack Built」。

把一個片語或子句放進另一個片語或子句裡的過程,稱為嵌入。 正是透過遞迴與嵌入的過程,我們才能取用有限數量的形式(詞與片語),建構出無限多種表達。 不僅如此,嵌入還讓我們能建構出無限長的結構,至少在理論上是如此。

這首童謠的內容如下:

This is the house that Jack built.

This is the malt
that lay in the house that Jack built.

This is the rat
that ate the malt
that lay in the house that Jack built.

This is the cat
that killed the rat
that ate the malt
that lay in the house that Jack built.

This is the dog
that worried the cat
that killed the rat
that ate the malt
that lay in the house that Jack built.

This is the cow with the crumpled horn
that tossed the dog
that worried the cat
that killed the rat
that ate the malt
that lay in the house that Jack built.

This is the maiden all forlorn
that milked the cow with the crumpled horn
that tossed the dog
that worried the cat
that killed the rat
that ate the malt
that lay in the house that Jack built.

This is the man all tattered and torn
that kissed the maiden all forlorn
that milked the cow with the crumpled horn
that tossed the dog
that worried the cat
that killed the rat
that ate the malt
that lay in the house that Jack built.

This is the priest all shaven and shorn
that married the man all tattered and torn
that kissed the maiden all forlorn
that milked the cow with the crumpled horn
that tossed the dog
that worried the cat
that killed the rat
that ate the malt
that lay in the house that Jack built.

This is the rooster that crowed in the morn
that woke the priest all shaven and shorn
that married the man all tattered and torn
that kissed the maiden all forlorn
that milked the cow with the crumpled horn
that tossed the dog
that worried the cat
that killed the rat
that ate the malt
that lay in the house that Jack built.

This is the farmer sowing his corn
that kept the rooster that crowed in the morn
that woke the priest all shaven and shorn
that married the man all tattered and torn
that kissed the maiden all forlorn
that milked the cow with the crumpled horn
that tossed the dog
that worried the cat
that killed the rat
that ate the malt
that lay in the house that Jack built.

This is the horse and the hound and the horn
that belonged to the farmer sowing his corn
that kept the rooster that crowed in the morn
that woke the priest all shaven and shorn
that married the man all tattered and torn
that kissed the maiden all forlorn
that milked the cow with the crumpled horn
that tossed the dog
that worried the cat
that killed the rat
that ate the malt
that lay in the house that Jack built.

提示

這個練習的重點是程式碼重構,所以我們直接提供一份已經通過測試的解法給你。

挑戰在於改寫它,直到你對自己的成果感到滿意,並在這個過程中學到一些東西。

如果你不知道從哪裡開始,這裡有一些想法:

  • 試著把重複的部分降到最低。
  • 試著讓程式碼更好閱讀。

慢慢來。

一次只改一個地方,並確認你的解法仍然能通過測試。

祝你玩得開心!


出處

英國童謠連結會在新視窗或分頁中開啟
透過 GitHub 編輯 連結會在新視窗或分頁中開啟
Haskell Exercism

準備好開始 房子 了嗎?

註冊 Exercism,透過 107 個練習 和真人引導來學習並精通 Haskell,全部免費。