singalen: (sun)
[personal profile] singalen
Присели наконец с [livejournal.com profile] vbayda поковырять Хаскелль и сделать хоть что-то. Довели до компилируемости примерчик с байндингом параметров функций. Чуть лучше запомнили приоритеты букварь - операторов и функций :)
Вспомнили:
1. Оператор $ - это оператор ленивого ("обычного") вызова функции.
2. Параметрический тип Maybe a: data Maybe a = Just a | Nothing;
Это "nullable", проверяемый компилятором - мечта одного моего знакомого для Джавы :)
3. Анонимные параметры функции (через pattern matching).
module Main
  where

import Data.List
import Data.Maybe

-- это описание типа данных - "записи" с конструктором и одним полем
data Entity = Entity { circle :: Circle }
data Position = Position { x, y :: Float }
data Circle = Circle { position :: Position, r :: Float }

circlesIntersect :: Circle -> Circle -> Bool
circlesIntersect c1 c2 = 
  sqr (r c1 + r c2) < 
    sqr ((x $ position c1) - (x $ position c2)) + sqr ((y $ position c1) - (y $ position c2))
  where sqr = (^2)

-- второй вариант, покороче.  
circlesIntersect2 :: Circle -> Circle -> Bool
circlesIntersect2 (Circle p1 r1) (Circle p2 r2) = 
  sqr (r1 + r2) < sqr (x p1 - x p2) + sqr (y p1 - y p2)
  where sqr = (^2)

-- найти первую (или никакую) entity, circle которой пересекается с указанным Circle.
findIntersecting :: Circle -> [Entity] -> Maybe Entity
findIntersecting theCircle entities =
  find entityMatches entities
  where
    entityMatches :: Entity -> Bool
    entityMatches e = circlesIntersect theCircle (circle e)

--findIntersecting theCircle entities =
--  find ((circlesIntersect theCircle) . circle) entities

(no subject)

11/2/07 13:02 (UTC)
Posted by [identity profile] nponeccop.livejournal.com
А протестировать забыли? У Вас "меньше" вместо "больше" везде :)

(no subject)

11/2/07 13:36 (UTC)
Posted by [identity profile] aleksijb.livejournal.com
Это поправимо, главное что компилится ;)