Namaran

Code daily. Without assist.

2026-08-23

EchoHead.hs

echoHead :: [a] -> [a]
-- write this: return the list with its head repeated once at the front
-- (e.g. echoHead [1,2,3] = [1,1,2,3]), or the list unchanged if it is
-- empty. Must stay a pure function -- no IO -- and use an as-pattern so
-- you don't have to write the list out twice.

echoHeadを実装してください。空でないリストの場合は先頭要素をもう一度だけ前に追加し、空リストならそのまま返します。リストを2度書き並べないよう、as-patternを使うこと。純粋関数のままにし、IOを使わないこと。

Reference
echoHead :: [a] -> [a]
echoHead whole@(x:_) = x : whole
echoHead [] = []

whole@(x:_)は「先頭要素をxとして取り出しつつ、リスト全体もwholeとして覚えておく」というas-patternです。これがあるおかげで、結果を組み立てるときx : x : xsのようにリストの残りを自分で書き直さずに、既に持っているwholeをそのままx : wholeとして使えます。echoHeadはどんな入力に対しても同じ結果を返し、副作用を持たない純粋関数のままです。これは参考実装であり、唯一の正解ではありません。