deniok: (Default)
deniok ([personal profile] deniok) wrote2012-11-27 12:36 pm

Haskell, newtype vs data

Сегодня на stackoverflow, отвечая на вопрос, Andreas Hammar привёл хорошие примеры. Сохраняю на будущее, как простые задачки для студентов
data    D a = D a
data    S a = S !a
newtype N a = N a

constD x (D y) = x
constS x (S y) = x
constN x (N y) = x
Какие из следующих вызовов завершат свою работу как Deep Thought, а какие как Earth?
D undefined `seq` 42
S undefined `seq` 42
N undefined `seq` 42
constD 42 undefined
constS 42 undefined
constN 42 undefined

[identity profile] lionet.livejournal.com 2012-11-27 08:39 am (UTC)(link)
newtype — это создание фантомного конструктора/тэга, которого потом в рантайме не существует. Фактически, «newtype N a» это то же самое, что «a» в рантайме. Отсюда взрывание третьего и невзрывание шестого примеров. Строгий !a в типе S приводит к попытке форсирования undefined во втором примере, поэтому он взрывается. Остальное стандартно.

[identity profile] deni-ok.livejournal.com 2012-11-27 08:48 am (UTC)(link)
ага, всё верно.

[identity profile] kurilka.livejournal.com 2012-11-28 01:13 pm (UTC)(link)
а что это за термины Deep Thought и Earth?

[identity profile] deni-ok.livejournal.com 2012-11-28 01:17 pm (UTC)(link)
из The Hitchhiker's Guide to the Galaxy. Deep Thought после семи с половиной миллионов лет раздумья ответил 42 на один вопрос, и пошло-поехало.

[identity profile] kurilka.livejournal.com 2012-11-28 01:23 pm (UTC)(link)
а земля-то тут при чём?

[identity profile] deni-ok.livejournal.com 2012-11-28 01:39 pm (UTC)(link)
Although often mistaken for a planet, Earth is in reality the greatest supercomputer of all time, designed by the second greatest supercomputer of all time, Deep Thought, to calculate the Ultimate Question of Life, The Universe and Everything (to which the answer is 42). It was built by the then-thriving custom planet industry of Magrathea to run a ten-million-year program in which organic life would play a major role.

Five minutes before the program was to finish running, Earth was destroyed by the Vogons, allegedly to make way for a hyperspace bypass but in fact to prevent the Ultimate Question being discovered, as it was seen as a threat to the psychiatric industry.

[identity profile] kurilka.livejournal.com 2012-11-28 01:42 pm (UTC)(link)
а, чот я совсем уже книжку позабыл, сорри

[identity profile] deni-ok.livejournal.com 2012-11-28 01:43 pm (UTC)(link)
Фильм посмотри, он вполне достоин книжки.

[identity profile] kurilka.livejournal.com 2012-11-28 01:49 pm (UTC)(link)
Не, мне он как-то не особо понравился в отличие от