POV-Ray : Newsgroups : povray.off-topic : A Haskell question... : Re: A Haskell question... Server Time
10 Oct 2024 21:15:28 EDT (-0400)
  Re: A Haskell question...  
From: Orchid XP v7
Date: 3 Feb 2008 04:15:23
Message: <47a5862b$1@news.povray.org>
Darren New wrote:
> How would you write this in Haskell?
> 
> struct Point {int x; int y;}

   data Point = Point {x, y :: Int}

Caution: Note that the names "x" and "y" must be unique within the 
entire module. For this reason, you'd probably use longer names.

For something like this, a "typical" Haskell approach would "probably" 
use unnamed fields:

   data Point = Point Int Int

In either case, the following are all valid:

   let p = Point 3 6 ...
   my_function (Point x y) = ...

If the fields are named, you can also write

   let p = Point {x=3, y=6} ...
   let p = Point {y=6, x=3} ...
   my_function p = ... x p ...

The expression "x p" is like the Pascal-style "p.x". (That is, "x" is a 
function that takes a Point and yields its X coordinate.)

> distance = sqrt(p.x*p.x + p.y*p.y);

   distance (Point x y) = sqrt (x*x + y*y)

> Then, is it possible to add a Z element to the "Point" type without 
> having to rewrite the "distance" part? (Sure, it'll give the wrong 
> answer, but that's the point I'm trying to make with someone elsewhere 
> claiming strong typing avoids this sort of error.)

If you change the function to

   distance p = sqrt (x p * x p + y p * y p)

then it will work with either of

   data Point = Point {x, y :: Int}
   data Point = Point {x, y, z :: Int}

If you're asking about having two seperate Point types in the same 
program... that's another story.

Clear?

-- 
http://blog.orphi.me.uk/
http://www.zazzle.com/MathematicalOrchid*


Post a reply to this message

Copyright 2003-2023 Persistence of Vision Raytracer Pty. Ltd.