Safe Haskell | None |
---|---|
Language | Haskell98 |
Standard.Debug
Description
The standard set of functions and variables available to all programs. This version is for debugging purposes only. Look at the documentation in the Standard module for more information.
Synopsis
- (++) :: [a] -> [a] -> [a]
- data Bool
- type Truth = Bool
- ifThenElse :: Truth -> a -> a -> a
- (==) :: a -> a -> Truth
- (/=) :: a -> a -> Truth
- (&&) :: Truth -> Truth -> Truth
- (||) :: Truth -> Truth -> Truth
- not :: Truth -> Truth
- otherwise :: Truth
- data Number
- fromDouble :: Double -> Number
- toDouble :: Number -> Double
- fromInteger :: Integer -> Number
- fromRational :: Rational -> Number
- fromInt :: Int -> Number
- toInt :: Number -> Int
- isInteger :: Number -> Truth
- (=~) :: Number -> Number -> Truth
- (+) :: Number -> Number -> Number
- (-) :: Number -> Number -> Number
- (*) :: Number -> Number -> Number
- (/) :: Number -> Number -> Number
- (^) :: Number -> Number -> Number
- (<) :: Number -> Number -> Truth
- (<=) :: Number -> Number -> Truth
- (>) :: Number -> Number -> Truth
- (>=) :: Number -> Number -> Truth
- max :: (Number, Number) -> Number
- min :: (Number, Number) -> Number
- negate :: Number -> Number
- abs :: Number -> Number
- absoluteValue :: Number -> Number
- signum :: Number -> Number
- truncated :: Number -> Number
- rounded :: Number -> Number
- ceiling :: Number -> Number
- floor :: Number -> Number
- quotient :: (Number, Number) -> Number
- remainder :: (Number, Number) -> Number
- pi :: Number
- exp :: Number -> Number
- sqrt :: Number -> Number
- squareRoot :: Number -> Number
- log :: Number -> Number
- logBase :: (Number, Number) -> Number
- sin :: Number -> Number
- tan :: Number -> Number
- cos :: Number -> Number
- asin :: Number -> Number
- acos :: Number -> Number
- atan :: Number -> Number
- properFraction :: Number -> (Number, Number)
- even :: Number -> Truth
- odd :: Number -> Truth
- gcd :: (Number, Number) -> Number
- lcm :: (Number, Number) -> Number
- sum :: [Number] -> Number
- product :: [Number] -> Number
- maximum :: [Number] -> Number
- minimum :: [Number] -> Number
- permutations :: [a] -> [[a]]
- subsequences :: [a] -> [[a]]
- data Text
- fromString :: String -> Text
- toString :: Text -> String
- (<>) :: Text -> Text -> Text
- numberOfCharacters :: Text -> Number
- numberOfWords :: Text -> Number
- numberOfLines :: Text -> Number
- lines :: Text -> [Text]
- unlines :: [Text] -> Text
- words :: Text -> [Text]
- unwords :: [Text] -> Text
- characters :: Text -> [Text]
- printed :: Number -> Text
- joined :: [Text] -> Text
- joinedWith :: ([Text], Text) -> Text
- lowercase :: Text -> Text
- uppercase :: Text -> Text
- startsWith :: (Text, Text) -> Truth
- endsWith :: (Text, Text) -> Truth
- substitution :: (Text, Text, Text) -> Text
- substitutions :: (Text, [(Text, Text)]) -> Text
- toOperator :: ((a, b) -> c) -> a -> b -> c
- fromOperator :: (a -> b -> c) -> (a, b) -> c
- firstOfPair :: (a, b) -> a
- secondOfPair :: (a, b) -> b
- error :: Text -> a
- undefined :: a
- fail :: String -> a
- empty :: [a] -> Truth
- contains :: ([a], a) -> Truth
- length :: [a] -> Number
- at :: ([a], a, Number) -> [a]
- (#) :: [a] -> Number -> a
- any :: [Truth] -> Truth
- all :: [Truth] -> Truth
- none :: [Truth] -> Truth
- repeated :: ([a], Number) -> [a]
- repeating :: [a] -> [a]
- first :: ([a], Number) -> [a]
- last :: ([a], Number) -> [a]
- rest :: ([a], Number) -> [a]
- groups :: ([a], Number) -> [[a]]
- while :: ([a], a -> Truth) -> [a]
- until :: ([a], a -> Truth) -> [a]
- after :: ([a], a -> Truth) -> [a]
- concatenated :: [[a]] -> [a]
- range :: Number -> [Number]
- sorted :: [Number] -> [Number]
- reversed :: [a] -> [a]
- unique :: [a] -> [a]
- transposed :: [[a]] -> [[a]]
- shuffled :: ([a], Number) -> [a]
- randomNumbers :: Number -> [Number]
- data Color
- pattern HSL :: (Number, Number, Number) -> Color
- pattern RGB :: (Number, Number, Number) -> Color
- pattern RGBA :: (Number, Number, Number, Number) -> Color
- mixed :: [Color] -> Color
- lighter :: (Color, Number) -> Color
- light :: Color -> Color
- darker :: (Color, Number) -> Color
- dark :: Color -> Color
- brighter :: (Color, Number) -> Color
- bright :: Color -> Color
- duller :: (Color, Number) -> Color
- dull :: Color -> Color
- translucent :: Color -> Color
- assortedColors :: [Color]
- hue :: Color -> Number
- saturation :: Color -> Number
- luminosity :: Color -> Number
- alpha :: Color -> Number
- rgb :: (Number, Number, Number) -> Color
- greyed :: Number -> Color
- withAlpha :: (Color, Number) -> Color
- colorNamed :: Text -> Color
- data TextStyle
- data Font
- data Picture
- type Vector = (Number, Number)
- type Point = (Number, Number)
- pictureBounds :: Picture -> (Point, Point)
- outputBounds :: (Point, Point)
- xCoord :: Point -> Number
- yCoord :: Point -> Number
- translatedPoint :: (Point, (Number, Number)) -> Point
- rotatedPoint :: (Point, Number) -> Point
- scaledPoint :: (Point, Number, Number) -> Point
- dilatedPoint :: (Point, Number) -> Point
- vectorLength :: Vector -> Number
- vectorDirection :: Vector -> Number
- vectorSum :: (Vector, Vector) -> Vector
- vectorDifference :: (Vector, Vector) -> Vector
- scaledVector :: (Vector, Number) -> Vector
- rotatedVector :: (Vector, Number) -> Vector
- dotProduct :: (Vector, Vector) -> Number
- blank :: Picture
- polyline :: [Point] -> Picture
- thickPolyline :: ([Point], Number) -> Picture
- polygon :: [Point] -> Picture
- thickPolygon :: ([Point], Number) -> Picture
- solidPolygon :: [Point] -> Picture
- curve :: [Point] -> Picture
- thickCurve :: ([Point], Number) -> Picture
- closedCurve :: [Point] -> Picture
- thickClosedCurve :: ([Point], Number) -> Picture
- solidClosedCurve :: [Point] -> Picture
- rectangle :: (Number, Number) -> Picture
- solidRectangle :: (Number, Number) -> Picture
- thickRectangle :: (Number, Number, Number) -> Picture
- circle :: Number -> Picture
- solidCircle :: Number -> Picture
- thickCircle :: (Number, Number) -> Picture
- arc :: (Number, Number, Number) -> Picture
- sector :: (Number, Number, Number) -> Picture
- thickArc :: (Number, Number, Number, Number) -> Picture
- lettering :: Text -> Picture
- styledLettering :: (Text, Font, TextStyle) -> Picture
- colored :: (Picture, Color) -> Picture
- translated :: (Picture, (Number, Number)) -> Picture
- scaled :: (Picture, Number, Number) -> Picture
- dilated :: (Picture, Number) -> Picture
- rotated :: (Picture, Number) -> Picture
- clipped :: (Picture, Number, Number) -> Picture
- combined :: [Picture] -> Picture
- painted :: (Picture, Text) -> Picture
- data Event
- = KeyPress !Text
- | KeyRelease !Text
- | PointerPress !Point
- | PointerRelease !Point
- | PointerMovement !Point
- | TextEntry !Text
- | TimePassing !Number
- type Effect = IO ()
- traced :: (a, Text) -> a
- activityOf :: ([Number] -> world, (world, Event) -> world, world -> Picture) -> Effect
- type Predicate t = t -> Truth
- type Animation = Number -> Picture
- dot :: Point -> Picture
- floating :: Picture -> Point -> Picture
- labeling :: (Number, Number, Number, Text) -> Picture
- right :: (Picture, Number) -> Picture
- up :: (Picture, Number) -> Picture
- rightPoint :: (Point, Number) -> Point
- upPoint :: (Point, Number) -> Point
- polylineEdges :: [Point] -> [(Point, Point)]
- polygonEdges :: [Point] -> [(Point, Point)]
- polygonPerimeter :: [Point] -> Number
- polygonArea :: [Point] -> Number
- polygonCenter :: [Point] -> Point
- polylineLength :: [Point] -> Number
- polygonCorners :: [Point] -> [(Point, Point, Point)]
- cornerAngles :: (Point, Point, Point) -> (Number, Number)
- saw :: (Number, Number) -> Number
- staticMotion :: Picture -> Animation
- repeatedMotion :: (Number, Animation) -> Animation
- delayedMotion :: (Number, Animation) -> Animation
- fasterMotion :: (Number, Animation) -> Animation
- transformedMotion :: (Picture -> Picture) -> Animation -> Animation
- combinedMotions :: [Animation] -> Animation
- showBetween :: (Number, Number, Animation) -> Animation
- travelBetween :: (Number, Number, Animation) -> Animation
- cloned :: object -> [object]
- distributed :: (a -> b, [a]) -> [b]
- iterated :: ((object, param) -> object, [param]) -> object -> [object]
- on :: (Truth, value, value) -> value
- newParams :: Params
- set :: (Text, Number) -> Params -> Params
- get :: (Text, Number) -> Params -> Number
- selected :: ([value], Predicate value) -> [value]
- selectedValues :: ([(key, value)], Predicate key) -> [value]
- selectedKeys :: ([(key, value)], Predicate value) -> [key]
- all_ :: [Predicate value] -> Predicate value
- any_ :: [Predicate value] -> Predicate value
- choices :: [(Predicate inv, outv)] -> inv -> [outv]
- choice :: ([(Predicate inv, outv)], outv) -> inv -> outv
- precedes :: Predicate (Text, Text)
- is_in :: [value] -> Predicate value
- nonEmpty :: Predicate [value]
- between :: (Number, Number) -> Predicate Number
- above :: Number -> Predicate Number
- below :: Number -> Predicate Number
- exactly :: value -> Predicate value
- excluded :: Predicate value -> Predicate value
- alphabeticalSortedOn :: (value -> Text, [value]) -> [value]
- numericalSortedOn :: (value -> Number, [value]) -> [value]
- logicalGroupBy :: (Predicate value, [value]) -> [(Truth, [value])]
- alphabeticalGroupBy :: (value -> Text, [value]) -> [(Text, [value])]
- numericalGroupBy :: (value -> Number, [value]) -> [(Number, [value])]
- run :: [value -> value] -> value -> value
- repeatFor :: (Number, value -> value) -> value -> value
- repeatWhile :: (Predicate value, value -> value) -> value -> value
- foreach :: ([input], input -> output) -> [output]
- forloop :: (state, Predicate state, state -> state, state -> output) -> [output]
- whileloop :: (state, Predicate state, state -> state, state -> output) -> output
- prepend :: (value, [value]) -> [value]
- append :: (value, [value]) -> [value]
- list :: (Number -> value) -> [value]
- listn :: (Number -> value, Number) -> [value]
- butLast :: ([value], Number) -> [value]
- pairs :: [value] -> [(value, value)]
- unpairs :: [(value, value)] -> [value]
- unzipped :: [(a, b)] -> ([a], [b])
- zipped :: ([a], [b]) -> [(a, b)]
- indexOf :: (value, [value]) -> Number
- lJustified :: (Text, Number) -> Text
- rJustified :: (Text, Number) -> Text
- printedDecimals :: (Number, Number) -> Text
- printedNumbers :: [Number] -> Text
- printedPoint :: Point -> Text
- letteringBlock :: [Text] -> Picture
- cumulativeSums :: [Number] -> [Number]
- pass :: value -> value
- textHash :: Text -> Number
- drawingOf :: Picture -> Effect
- animationOf :: (Number -> Picture, Number) -> Effect
- slideshow :: ([Picture], Number) -> Effect
Documentation
Instances
Bounded Bool | |
Enum Bool | |
Eq Bool | |
Ord Bool | |
Read Bool | |
Show Bool | |
Ix Bool | |
Generic Bool | |
Lift Bool | |
Defined in Language.Haskell.TH.Syntax | |
Bits Bool | |
Defined in Data.Bits | |
FiniteBits Bool | |
Defined in Data.Bits Methods finiteBitSize :: Bool -> Int countLeadingZeros :: Bool -> Int countTrailingZeros :: Bool -> Int | |
Random Bool | |
Unbox Bool | |
Defined in Data.Vector.Unboxed.Base | |
IsAddEventListenerOptionsOrBool Bool | |
Defined in GHCJS.DOM.Types | |
IsEventListenerOptionsOrBool Bool | |
Defined in GHCJS.DOM.Types | |
SingKind Bool | |
Defined in GHC.Generics Associated Types type DemoteRep Bool :: Type | |
Vector Vector Bool | |
Defined in Data.Vector.Unboxed.Base Methods basicUnsafeFreeze :: PrimMonad m => Mutable Vector (PrimState m) Bool -> m (Vector Bool) basicUnsafeThaw :: PrimMonad m => Vector Bool -> m (Mutable Vector (PrimState m) Bool) basicLength :: Vector Bool -> Int basicUnsafeSlice :: Int -> Int -> Vector Bool -> Vector Bool basicUnsafeIndexM :: Monad m => Vector Bool -> Int -> m Bool basicUnsafeCopy :: PrimMonad m => Mutable Vector (PrimState m) Bool -> Vector Bool -> m () | |
MVector MVector Bool | |
Defined in Data.Vector.Unboxed.Base Methods basicLength :: MVector s Bool -> Int basicUnsafeSlice :: Int -> Int -> MVector s Bool -> MVector s Bool basicOverlaps :: MVector s Bool -> MVector s Bool -> Bool basicUnsafeNew :: PrimMonad m => Int -> m (MVector (PrimState m) Bool) basicInitialize :: PrimMonad m => MVector (PrimState m) Bool -> m () basicUnsafeReplicate :: PrimMonad m => Int -> Bool -> m (MVector (PrimState m) Bool) basicUnsafeRead :: PrimMonad m => MVector (PrimState m) Bool -> Int -> m Bool basicUnsafeWrite :: PrimMonad m => MVector (PrimState m) Bool -> Int -> Bool -> m () basicClear :: PrimMonad m => MVector (PrimState m) Bool -> m () basicSet :: PrimMonad m => MVector (PrimState m) Bool -> Bool -> m () basicUnsafeCopy :: PrimMonad m => MVector (PrimState m) Bool -> MVector (PrimState m) Bool -> m () basicUnsafeMove :: PrimMonad m => MVector (PrimState m) Bool -> MVector (PrimState m) Bool -> m () basicUnsafeGrow :: PrimMonad m => MVector (PrimState m) Bool -> Int -> m (MVector (PrimState m) Bool) | |
SingI False | |
Defined in GHC.Generics | |
SingI True | |
Defined in GHC.Generics | |
type Rep Bool | |
Defined in GHC.Generics | |
newtype Vector Bool | |
Defined in Data.Vector.Unboxed.Base | |
type DemoteRep Bool | |
Defined in GHC.Generics | |
data Sing (a :: Bool) | |
newtype MVector s Bool | |
Defined in Data.Vector.Unboxed.Base |
ifThenElse :: Truth -> a -> a -> a #
(/=) :: a -> a -> Truth infix 4 #
Compares values to see if they are not equal.
Note that a /= b
is the same as not (a == b)
.
The type for numbers.
Numbers can be positive or negative, whole or fractional. For example, 5, 3.2, and -10 are all values of the type Number.
Instances
Enum Number # | |
Eq Number # | |
Floating Number # | |
Fractional Number # | |
Defined in Internal.Num | |
Num Number # | |
Ord Number # | |
Real Number # | |
Defined in Internal.Num Methods toRational :: Number -> Rational | |
RealFloat Number # | |
Defined in Internal.Num Methods floatRadix :: Number -> Integer floatDigits :: Number -> Int floatRange :: Number -> (Int, Int) decodeFloat :: Number -> (Integer, Int) encodeFloat :: Integer -> Int -> Number significand :: Number -> Number scaleFloat :: Int -> Number -> Number isInfinite :: Number -> Bool isDenormalized :: Number -> Bool isNegativeZero :: Number -> Bool | |
RealFrac Number # | |
Show Number # | |
fromDouble :: Double -> Number #
fromInteger :: Integer -> Number #
fromRational :: Rational -> Number #
isInteger :: Number -> Truth #
Tells whether a Number is an integer or not.
An integer is a whole number, such as 5, 0, or -10. Numbers with non-zero decimals, like 5.3, are not integers.
(/) :: Number -> Number -> Number infixl 7 #
Divides two numbers. The second number should not be zero.
(<=) :: Number -> Number -> Truth infix 4 #
Tells whether one number is less than or equal to the other.
(>=) :: Number -> Number -> Truth infix 4 #
Tells whether one number is greater than or equal to the other.
Gives the absolute value of a number.
If the number if positive or zero, the absolute value is the same as the number. If the number is negative, the absolute value is the opposite of the number.
absoluteValue :: Number -> Number #
truncated :: Number -> Number #
Gives the number without its fractional part.
For example, truncated(4.2) is 4, while truncated(-4.7) is -4.
Gives the number rounded to the nearest integer.
For example, round(4.2) is 4, while round(4.7) is 5.
Gives the smallest integer that is greater than or equal to a number.
For example, ceiling(4) is 4, while ceiling(4.1) is 5. With negative numbers, ceiling(-3.5) is -3, since -3 is greater than -3.5.
Gives the largest integer that is less than or equal to a number.
For example, floor(4) is 4, while floor(3.9) is 3. With negative numbers, floor(-3.5) is -4, since -4 is less than -3.5.
quotient :: (Number, Number) -> Number #
Gives the integer part of the result when dividing two numbers.
For example, 3/2 is 1.5, but quotient(3, 2) is 1, which is the integer part.
remainder :: (Number, Number) -> Number #
Gives the remainder when dividing two numbers.
For example, remainder(3,2) is 1, which is the remainder when dividing 3 by 2.
The constant pi, which is equal to the ratio between the circumference and diameter of a circle.
pi is approximately 3.14.
Gives the exponential of a number. This is equal to the constant e, raised to the power of the number.
The exp function increases faster and faster very quickly. For example, if t is the current time in seconds, exp(t) will reach a million in about 14 seconds. It will reach a billion in around 21 seconds.
Gives the square root of a number. This is the positive number that, when multiplied by itself, gives the original number back.
The sqrt always increases, but slows down. For example, if t is the current time, sqrt(t) will reach 5 in 25 seconds. But it will take 100 seconds to reach 10, and 225 seconds (almost 4 minutes) to reach 15.
squareRoot :: Number -> Number #
Gives the natural log of a number. This is the opposite of the exp function.
Like sqrt, the log function always increases, but slows down. However, it slows down much sooner than the sqrt function. If t is the current time in seconds, it takes more than 2 minutes for log(t) to reach 5, and more than 6 hours to reach 10!
logBase :: (Number, Number) -> Number #
Gives the logarithm of the first number, using the base of the second number.
Gives the tangent of an angle, where the angle is measured in degrees.
This is the slope of a line at that angle from horizontal.
Gives the inverse sine of a value, in degrees.
This is the unique angle between -90 and 90 that has the input as its sine.
Gives the inverse cosine of a value, in degrees.
This is the unique angle between 0 and 180 that has the input as its cosine.
Gives the inverse tangent of a value, in degrees.
This is the unique angle between -90 and 90 that has the input as its tangent.
properFraction :: Number -> (Number, Number) #
Separates a number into its whole and fractional parts.
For example, properFraction(1.2) is (1, 0.2).
gcd :: (Number, Number) -> Number #
Gives the greatest common divisor of two numbers.
This is the largest number that divides each of the two parameters. Both parameters must be integers.
lcm :: (Number, Number) -> Number #
Gives the least common multiple of two numbers.
This is the smallest number that is divisible by both of the two parameters. Both parameters must be integers.
permutations :: [a] -> [[a]] #
subsequences :: [a] -> [[a]] #
fromString :: String -> Text #
numberOfCharacters :: Text -> Number #
numberOfWords :: Text -> Number #
numberOfLines :: Text -> Number #
characters :: Text -> [Text] #
joinedWith :: ([Text], Text) -> Text #
startsWith :: (Text, Text) -> Truth #
substitution :: (Text, Text, Text) -> Text #
Gives the result of replacing one piece of text with another.
For example, substitution("How do you do?", "do", "be")
is equal to
"How be you be?"
.
substitutions :: (Text, [(Text, Text)]) -> Text #
Gives the result of performing many substitutions in a piece of text. This is commonly used to build text to show in a program, as in this example:
substitutions("Lives: [lives] of 3 Score: [score]", [("[lives]", printed(lives)), ("[score]", printed(score))])
toOperator :: ((a, b) -> c) -> a -> b -> c #
Converts a function to an operator.
Example use:
f(x,y) = 2*x + y (%) = toOperator(f) eight = 3 % 2
This has the same effect as defining % as:
x % y = 2*x + y eight = 3 % 2
fromOperator :: (a -> b -> c) -> (a, b) -> c #
Converts an operator into a normal function.
Example use:
divide = fromOperator(/) four = divide(16, 4)
firstOfPair :: (a, b) -> a #
Returns the first element of an ordered pair.
secondOfPair :: (a, b) -> b #
Returns the second element of an ordered pair.
Represents an undefined value. This lets you compile programs with unfinished values. If the value is needed, the program will crash.
Fails with an error message. This is required (though apparently unused) by the desugaring for pattern binds in list comprehensions.
at :: ([a], a, Number) -> [a] #
Gives a list with a replaced element at an index. Indices start at 1.
(#) :: [a] -> Number -> a infixl 8 #
Gives the member of a list at a given index. Indices start at 1.
Determines if any proposition in a list is true.
For example, any([even(n) | n <- [1,2,3]])
is True
, because 2 is even.
Determines if all propositions in a list are true.
For example, all([even(n) | n <- [2,3,4]])
is False
, because 3 is not even.
Determines if all propositions in a list are false.
For example, none([odd(n) | n <- [2,3,4]])
is False
, because 3 is odd.
rest :: ([a], Number) -> [a] #
Gives all members of a list after the given number.
In general, xs = first(xs, n) ++ rest(xs, n)
.
groups :: ([a], Number) -> [[a]] #
Converts a list of elements into a list of smaller lists, each of the given length.
For example, [ (x, y) | [x, y] <- groups(randomNumbers(42), 2) ]
.
while :: ([a], a -> Truth) -> [a] #
Gives the longest prefix of a list for which a condition is true.
For example, while([2,4,5,6], even) = [2,4]
.
until :: ([a], a -> Truth) -> [a] #
Gives the longest prefix of a list for which a condition is false.
For example, until([2,4,5,6], odd) = [2,4]
.
after :: ([a], a -> Truth) -> [a] #
Gives the remaining portion of a list after the longest prefix for which a condition is true.
In general, xs = while(xs, cond) ++ after(xs, cond)
.
concatenated :: [[a]] -> [a] #
Gives the concatenation of all of the lists in its input.
range(number)
is a list of integers that increase between 1 and
number
, both included. If number
is less than 1, the list is empty.
Arguments with decimals are truncated.
transposed :: [[a]] -> [[a]] #
randomNumbers :: Number -> [Number] #
A random number generator. The Number
passed as input is known as
the seed, and it is used to generate a fresh new list of random numbers,
so that different seeds will generate different random numbers.
The numbers generated are not really random, but pseudorandom, which means
they are good enough to appear random to a human, but they will fail
statistical tests for real randomness.
A color.
Colors can be described in two ways:
- Constructing colors from coordinates in a color space, such
as
RGB
,RGBA
, orHSL
. - Using color names with the function
colorNamed
- Transforming other colors with functions such as
light
,dark
,bright
,dull
,translucent
,withAlpha
andmixed
.
Note that transparency is included in a color. However,
the RGB
and HSL
constructors only produce opaque
colors, but the RGBA
constructor and the functions
translucent
and withAlpha
work with transparency.
Produces a color by mixing other colors in equal proportion.
The order of colors is unimportant. Colors may be mixed in uneven
proportions by listing a color more than once, such as
mixed([red, red, orange])
.
lighter :: (Color, Number) -> Color #
Increases the luminosity of a color by the given amount.
The amount should be between -1 and 1, where:
lighter(c, 1)
is always white, regardless ofc
.lighter(c, 0)
is the same asc
.lighter(c, -1)
is always black, regardless ofc
.
Produces a lighter shade of the given color.
This function may be nested more than once to produce an even
lighter shade, as in light(light(blue))
.
darker :: (Color, Number) -> Color #
Decreases the luminosity of a color by the given amount.
The amount should be between -1 and 1, where:
darker(c, 1)
is always black, regardless ofc
.darker(c, 0)
is the same asc
.darker(c, -1)
is always white, regardless ofc
.
Produces a darker shade of the given color.
This function may be nested more than once to produce an even
darker shade, as in dark(dark(green))
.
brighter :: (Color, Number) -> Color #
Increases the saturation of a color by the given amount.
The amount should be between -1 and 1, where:
brighter(c, 1)
is a fully saturated version ofc
.brighter(c, 0)
is the same asc
.brighter(c, -1)
is just a shade of gray with no color.
Produces a brighter shade of the given color; that is, less gray and more colorful.
This function may be nested more than once to produce an even
brighter shade, as in bright(bright(yellow))
.
duller :: (Color, Number) -> Color #
Decreases the saturation of a color by the given amount.
The amount should be between -1 and 1, where:
duller(c, 1)
is just a shade of gray with no color.duller(c, 0)
is the same asc
.duller(c, -1)
is a fully saturated version ofc
.
Produces a duller shade of the given color; that is, more gray and less colorful.
This function may be nested more than once to produce an even
duller shade, as in dull(dull(purple))
.
translucent :: Color -> Color #
Produces a partially transparent color.
This function may be nested more than once to produce an even
more transparent color, as in translucent(translucent(brown))
.
assortedColors :: [Color] #
An infinite list of various colors.
The list is chosen to contain a variety of different hues as spread out as possible to create colorful effects.
saturation :: Color -> Number #
luminosity :: Color -> Number #
rgb :: (Number, Number, Number) -> Color #
This function allows you to specify color components in the range 0 to 255 instead of 0 to 1.
A shade of grey as given by the argument, where greyed(0)
is black
and greyed(1)
is white.
withAlpha :: (Color, Number) -> Color #
This function allows you to specify the level of transparency of the given color. Transparency must be given in the range 0 (fully transparent) to 1 (fully opaque).
colorNamed :: Text -> Color #
Convert the name of a color to the actual color. The name of the color can be specified in two ways. First, you can use the official CSS color, as defined in the working document CSS Color Module Level 4, which can be found at https://drafts.csswg.org/css-color/#named-colors. You can also specify the color as a Text with the pattern "#xxxxxx", where the first character is a hash tag and the rest are 6 hexadecimal digits that correspond to the hex color, as usually defined in HTML documents.
The list of named colors is:
aliceblue
, antiquewhite
, aqua
, aquamarine
, azure
, beige
,
bisque
, black
, blanchedalmond
, blue
, blueviolet
, brown
,
burlywood
, cadetblue
, chartreuse
, chocolate
, coral
,
cornflowerblue
, cornsilk
, crimson
, cyan
, darkblue
,
darkcyan
, darkgoldenrod
, darkgray
, darkgreen
, darkgrey
,
darkkhaki
, darkmagenta
, darkolivegreen
, darkorange
,
darkorchid
, darkred
, darksalmon
, darkseagreen
, darkslateblue
,
darkslategray
, darkslategrey
, darkturquoise
, darkviolet
,
deeppink
, deepskyblue
, dimgray
, dimgrey
, dodgerblue
,
dustyred
,
firebrick
, floralwhite
, forestgreen
, fuchsia
, gainsboro
,
ghostwhite
, gold
, goldenrod
, gray
, green
, greenyellow
,
grey
, honeydew
, hotpink
, indigo
, ivory
,
khaki
, lavender
, lavenderblush
, lawngreen
, lemonchiffon
,
lightblue
, lightcoral
, lightcyan
, lightgoldenrodyellow
,
lightgray
, lightgreen
, lightgrey
, lightpink
, lightsalmon
,
lightseagreen
, lightskyblue
, lightslategray
, lightslategrey
,
lightsteelblue
, lighttan
, lightyellow
, lime
, limegreen
, linen
,
magenta
, maroon
, mediumaquamarine
, mediumblue
, mediumorchid
,
mediumpurple
, mediumseagreen
, mediumslateblue
, mediumspringgreen
,
mediumtan
, mediumturquoise
, mediumvioletred
, midnightblue
,
mintcream
, mistyrose
, navy
, oldlace
, olive
,
olivedrab
, orange
, orangered
, orchid
, palegoldenrod
,
palegreen
, paleturquoise
, palevioletred
, papayawhip
,
peachpuff
, peru
, pink
, plum
, powderblue
, purple
,
rebeccapurple
, red
, rosybrown
, royalblue
, saddlebrown
, salmon
,
sandybrown
, seagreen
, seashell
, sienna
, silver
, skyblue
,
slateblue
, slategray
, slategrey
, snow
, springgreen
, steelblue
,
tan
, teal
, thistle
, tomato
, turquoise
, violet
, wheat
, white
,
whitesmoke
, yellow
, and yellowgreen
.
A style in which lettering can be drawn. Text styles are used
with the styledLettering
function.
A font in which lettering can be drawn. Fonts are used with the
styledLettering
function.
NamedFont
may create a program that only works correctly on
computers where that font is installed, so you are encouraged to
use one of the other values.
A type for pictures.
Pictures can be created from geometry functions such as circle
and rectangle
. They can be combined using the function combined
.
They can be modified using transformations like translated
,
rotated
, dilated
, colored
, and scaled
. Ultimately, a picture
can be drawn on the screen using one of the CodeWorld entry points
such as drawingOf
.
type Point = (Number, Number) #
A point in two dimensions. A point is written with the x coordinate first and the y coordinate second. For example, (3, -2) is the point with x coordinate 3 and y coordinate -2.
pictureBounds :: Picture -> (Point, Point) #
The coordinates of the bottom-left and the top-right corners of a box that contains the given picture. The bounds are exact when the picture is made of straight line shapes only, but they may be larger or smaller than necessary in other cases.
outputBounds :: (Point, Point) #
The coordinates of the bottom-left and the top-right corners of the output window.
rotatedPoint :: (Point, Number) -> Point #
Rotates a given point by given angle, in degrees
scaledPoint :: (Point, Number, Number) -> Point #
Scales a given point by given x and y scaling factor. Scaling by a negative factor also reflects across that axis.
dilatedPoint :: (Point, Number) -> Point #
Dilates a given point by given uniform scaling factor. Dilating by a negative factor also reflects across the origin.
vectorLength :: Vector -> Number #
The length of the given vector
vectorDirection :: Vector -> Number #
The counter-clockwise angle, in degrees, that a given vector make with the X-axis
vectorDifference :: (Vector, Vector) -> Vector #
The difference of two vectors
scaledVector :: (Vector, Number) -> Vector #
Scales a given vector by a given scalar multiplier
rotatedVector :: (Vector, Number) -> Vector #
Rotates a given vector by a given angle in radians
dotProduct :: (Vector, Vector) -> Number #
The dot product of two vectors
thickPolyline :: ([Point], Number) -> Picture #
A thin sequence of line segments, with these endpoints and line width
thickPolygon :: ([Point], Number) -> Picture #
A thin polygon with these points as vertices
solidPolygon :: [Point] -> Picture #
A solid polygon with these points as vertices
thickCurve :: ([Point], Number) -> Picture #
A thick curve passing through these points, with this line width
closedCurve :: [Point] -> Picture #
A thin closed curve passing through these points.
thickClosedCurve :: ([Point], Number) -> Picture #
A thick closed curve passing through these points, with this line width.
solidClosedCurve :: [Point] -> Picture #
A solid closed curve passing through these points.
solidRectangle :: (Number, Number) -> Picture #
A solid rectangle, with this width and height
thickRectangle :: (Number, Number, Number) -> Picture #
A thick rectangle, with this width and height and line width
solidCircle :: Number -> Picture #
A solid circle, with this radius
thickCircle :: (Number, Number) -> Picture #
A thick circle, with this radius and line width
arc :: (Number, Number, Number) -> Picture #
A thin arc, starting and ending at these angles, with this radius
sector :: (Number, Number, Number) -> Picture #
A solid sector of a circle (i.e., a pie slice) starting and ending at these angles, with this radius
thickArc :: (Number, Number, Number, Number) -> Picture #
A thick arc, starting and ending at these angles, with this radius and line width
styledLettering :: (Text, Font, TextStyle) -> Picture #
A rendering of text characters, with a specific choice of font and style.
translated :: (Picture, (Number, Number)) -> Picture #
A copy of the given Picture translated by the given horizontal and vertical displacements.
scaled :: (Picture, Number, Number) -> Picture #
A picture scaled by these factors in the x and y directions.
Factors greater than 1
stretch the picture larger in that direction, and
less than 1
squish it smaller in that direction.
Negative factors also reflect the picture across that axis. For example, to mirror
a picture over the x-axis: scaled(p, -1, 1)
.
dilated :: (Picture, Number) -> Picture #
A picture with both dimensions scaled by the given factor.
Factors greater than 1
make the picture bigger and less than 1
make it smaller.
Negative factors reflect the picture across the origin, which is the same as rotating it by 180 degrees.
clipped :: (Picture, Number, Number) -> Picture #
A picture clipped to a rectangle of this width and height.
combined :: [Picture] -> Picture #
A picture made by combining the given list of pictures, so that the elements of the list are laid out from front to back. In other words, the first element of the list will be shown over the rest, and the last element of the list will be shown under all the previous ones. If the elements overlap, different orderings of the list will produce different results when drawn.
painted :: (Picture, Text) -> Picture #
The given picture painted with the color corresponding to the given
color name, which must be a valid argument of the colorNamed
function.
An event initiated by the user.
Values of this type represent events that the user triggers when using an interactive program.
Key events describe the key as Text
. Most keys are represented
by a single character text string, with the capital letter or other
symbol from the key. Keys that don't correspond to a single
character use longer names from the following list. Keep in mind
that not all of these keys appear on all keyboards.
- Up, Down, Left, and Right for the cursor keys.
- F1, F2, etc. for function keys.
- Backspace
- Tab
- Enter
- Shift
- Ctrl
- Alt
- Esc
- PageUp
- PageDown
- End
- Home
- Insert
- Delete
- CapsLock
- NumLock
- ScrollLock
- PrintScreen
- Break
- Separator
- Cancel
- Help
Constructors
KeyPress !Text | |
KeyRelease !Text | |
PointerPress !Point | |
PointerRelease !Point | |
PointerMovement !Point | |
TextEntry !Text | |
TimePassing !Number |
An effect is an operation that can be observed in the real world
A program ultimately needs to have an effect on the real world, such as showing a picture on a screen, or reacting when the user presses a key, taps on a pointer-sensitive display, or moves the mouse.
The type Effect
represents an action on the world outside
the internal memory of the computer. Entry points, such
as drawingOf
, will always produce effects, because a program
with no effect is useless. The word IO
is a shortcut for
Input/Output, given that effects can be thought as inputs from the
real world or outputs to the real world.
activityOf :: ([Number] -> world, (world, Event) -> world, world -> Picture) -> Effect #
A program that can interact with a user by responding to pointer and keyboard events and remember state.
To create an activity, you first choose a type for its state, called the "world" type. You will then describe the activity with three arguments:
- A function to create an initial world. The argument to this function is an infinite sequence of random numbers, which you can use to create a randomly chosen world.
- A function that describes how the world changes when
things happen. The function receives an old world and
an
Event
that occurs, and maps it to a new world. - A function that converts a world into a
Picture
, used to display the program on the screen.
For example:
program = activityOf(initial, change, picture) initial(rs) = 0 change(x, KeyPress("A")) = x - 1 change(x, KeyPress("D")) = x + 1 change(x, other) = x picture(x) = translated(solidCircle(1), x, 0)
In mathematical language, an activity is called a dynamical
system. The world type is known as the phase space of the
system, and the change
function is called the dynamics of
the system. The initial
and picture
functions are not
part of the system, but describe how the program should
simulate and display it.
type Predicate t = t -> Truth #
A predicate is a function that separates all possible values of a given
type t
into two groups: those for which the predicate is True
and those
for which the predicate is False
when it is applied to them.
type Animation = Number -> Picture #
You can simulate motion by specifying slightly different pictures at different instants in time (measured in seconds). Thus, an animation is just a function of time that specifies which picture to show at each time.
floating :: Picture -> Point -> Picture #
Applying floating
to any Picture
converts it to a function
similar to dot
. In other words, floating(picture)
is a function
that expects a Point
and produces a copy of the given picture
at that Point
. That Point
is sometimes called the anchor
,
and so we say that the floating picture is anchored at the given point.
Examples:
offCenterBird = floating(bird)(8,8) -- direct use
offCenterBird = floatingBird(8,8) where floatingBird = floating(bird) -- indirect use
The indirect use should be the normal use of this function, because
the direct use is better served with the function translated
labeling :: (Number, Number, Number, Text) -> Picture #
labeling(x,y,fontsize,text)
is like lettering(text)
, but it shows the
given text
with the given fontsize
at the given coordinates x
and y
.
This is just a convenience function to avoid the very common case
of nesting lettering
, translated
and dilated
.
right :: (Picture, Number) -> Picture #
A copy of the given picture
that is shown the given number of units
to the right of the original one.
up :: (Picture, Number) -> Picture #
A copy of the given picture
that is shown the given number of units
up from the original one.
rightPoint :: (Point, Number) -> Point #
polylineEdges :: [Point] -> [(Point, Point)] #
A list of the edges of the polygonal line determined by the given points. An edge is represented by a pair of points.
polygonEdges :: [Point] -> [(Point, Point)] #
A list of the edges of the closed polygon determined by the given points. An edge is represented by a pair of points.
polygonPerimeter :: [Point] -> Number #
The perimeter of the polygon determined by the given points
polygonArea :: [Point] -> Number #
The area of the polygon determined by the given points. If the polygon intersects itself, the area calculated by this function may not be what you expected, because there are several incompatible ways to calculate areas of self-intersecting polygons.
polygonCenter :: [Point] -> Point #
The coordinates of the geometric center (cf. https://en.wikipedia.org/wiki/Centroid) of the given points. This function will fail if no points are given.
polylineLength :: [Point] -> Number #
The total length of the polygonal line determined by the given points.
polygonCorners :: [Point] -> [(Point, Point, Point)] #
A list of triples where each vertex of a polygon is listed along with the
preceding and the succeeding vertex. The order of vertices in each triple is
(preceeding,current,succeeding)
.
cornerAngles :: (Point, Point, Point) -> (Number, Number) #
This function takes a list of corners, as calculated by polygonCorners
,
and returns the angles for an arc that spans the corresponding
vertex. If the list of corners is given so that the interior of the polygon
is at the left when traversing it, then the arcs will correspond to the
interior angles of the polygon.
saw :: (Number, Number) -> Number #
The expression saw(t,p)
is 0
when t=0
, increases up to 1 when t=p/2
, and then decreases back
to 0 when t=p
.
This increasing and decreasing when t
goes from 0
to p
is called
an oscillation of period p
. The oscillations will keep repeating,
so that the function is 0
when t
is 0,p,2p,3p,4p,5p,...
and it is 1 when t
is p/2
, 3p/2
, 5p/2
, 7p/2
, ...
staticMotion :: Picture -> Animation #
An animation that just shows the same static picture at all times
repeatedMotion :: (Number, Animation) -> Animation #
repeatedMotion(period,motion)
repeats the given motion
every
period
seconds. The motion
should begin at time 0 and end at time 1.
delayedMotion :: (Number, Animation) -> Animation #
delayedMotion(delay,motion)
delays the start of the given motion
until dealy
seconds have passed.
fasterMotion :: (Number, Animation) -> Animation #
fasterMotion(factor,motion)
will play the given motion
factor
times
faster than normal. If factor
is a number between 0 and 1, then motion
will actually play slower than normal.
transformedMotion :: (Picture -> Picture) -> Animation -> Animation #
Apply the given transformation to an animation. Since most transformations
have additional parameters, you will need to use the functions fixed1
or
fixed2
to add those parameters.
Example:
shiftedRight = transformedMotion(fixed2(right,5)) -- move an animation to the right
animation1 = circle -- A circle centered at the origin that grows with time
animation2 = shiftedRight(animation1) -- A circle centered at (5,0) that grows
combinedMotions :: [Animation] -> Animation #
This function is similar to combined
, but it combines animations
showBetween :: (Number, Number, Animation) -> Animation #
showBetween(start,finish,motion)
shows motion
only when time is
between start
and finish
. The motion
should be defined
so that it begins at time 0 and ends at time 1. It will then be
automatically adjusted, so that it begins at time start
and ends at
time finish
.
travelBetween :: (Number, Number, Animation) -> Animation #
This function is similar to showBetween
, but it will show
the initial picture motion(0)
before the start time, and it
will show the final picture motion(1)
after the finish time.
distributed :: (a -> b, [a]) -> [b] #
distributed(transformation,objects)
is a list of
objects, where each object is created by applying the given
transformation
to each object in the given list of objects
.
iterated :: ((object, param) -> object, [param]) -> object -> [object] #
iterated(transform,[parameter0,parameter1,...])
is a list
where each element
is the result of applying the given transform
with a
parameter
to the previous element. The given parameter list is
consumed sequentially, so that each new application
uses a new parameter
.
When an initial object0
comes from a pipeline, the result is
[object0, object1, object2, ... ]
where
object1
is transform(object0, parameter0)
,
object2
is transform(object1, parameter1)
and so on.
on :: (Truth, value, value) -> value #
Select the second argument when the first argument is True, and select the third argument when the first argument is False
selected :: ([value], Predicate value) -> [value] #
A list of values selected from the given list. A value is selected if it satisfies the given predicate. Otherwise, it is discarded.
selectedValues :: ([(key, value)], Predicate key) -> [value] #
A list of values selected form the given key-value list. A value is selected if the corresponding key satisfies the given predicate. This function is useful in lookup tables.
selectedKeys :: ([(key, value)], Predicate value) -> [key] #
A list of keys selected form the given key-value list. A key is selected if the corresponding value satisfies the given predicate. This function is useful to do reverse lookups in tables.
all_ :: [Predicate value] -> Predicate value #
A predicate that holds whenever all the given predicates
hold.
The trailing underscore in the function name is included
to distinguish it from the predicate named all
.
any_ :: [Predicate value] -> Predicate value #
A predicate that holds whenever at least one of the given
predicates holds.
The trailing underscore in the function name is included
to distinguish it from the predicate named any
.
choices :: [(Predicate inv, outv)] -> inv -> [outv] #
choices(options)
converts a given input into
a list of outputs according to the rules given.
Each rule has a predicate and an output value.
If the input satisfies a predicate, the corresponding
output value is included in the result.
Example:
test = choices([ (above(100),"You have fever") , (beween(97,100), "Your temperature is normal") , (below(97), "You have hypothermia") , (between(96,110), "You are alive") ]) message = test(102) -- ["You have fever", "You are alive"]
choice :: ([(Predicate inv, outv)], outv) -> inv -> outv #
choice(rules,default)
is similar to choices
, but
it produces just the first result that matches the rules.
If no rule matches, then the result is the given default.
precedes :: Predicate (Text, Text) #
precedes(text1,text2)
is True
whenever text1
precedes text2
alphabetically. It is False
otherwise.
When the two texts are the same,
the result of precedes
is False
.
is_in :: [value] -> Predicate value #
A predicate that can be applied to an argument to check whether
it is contained in the given list
.
Example:
selected([1..10],is_in([0,2..100]) -- is [2,4,6,8,10]
between :: (Number, Number) -> Predicate Number #
A predicate that is True
when the argument is between
the first parameter (included) and the second parameter (excluded).
In other words, between(a,b)(value)
holds whenever
a <= value
and value < b
above :: Number -> Predicate Number #
A predicate that is True
when the argument is above
the given parameter (included).
In other words, above(b)(value)
holds whenever
b <= value
below :: Number -> Predicate Number #
A predicate that is True
when the argument is below
the given parameter (excluded).
In other words, below(a)(value)
holds whenever
value < a
exactly :: value -> Predicate value #
A predicate that is True
when the argument is equal to
the given parameter.
In other words, exactly(a)(value)
holds whenever
value == a
excluded :: Predicate value -> Predicate value #
A predicate that is True
whenever the given predicate
is False
.
In other words, excluded(pred)(value)
holds whenever
pred(value)
does not hold.
alphabeticalSortedOn :: (value -> Text, [value]) -> [value] #
alphabeticalSortedOn(key, list)
is a list that has the same values as
the given list
, but the values are sorted in the
following way: if key(value1)
precedes key(value2)
alphabetically
then value1
will apear before value2
numericalSortedOn :: (value -> Number, [value]) -> [value] #
numericalSortedOn(key, list)
is a list that has the same values as the
given list
, but the values are sorted in the following
way: if key(value1) < key(value2)
then value1
will apear before
value2
logicalGroupBy :: (Predicate value, [value]) -> [(Truth, [value])] #
logicalGroupBy(predicate, list)
breaks up the given list
into
two sublists: one with the elements that satisfy the given predicate
and another with the elements that do not satisfy the given predicate
.
Neither the order of the elements in each
sublist nor the order of each sublist in the output list is specified,
so you cannot make any assumption about the order in which elements
will be present in the result.
Example:
logicalGroupBy(even, [1,2,3,4]) -- is [ (True,[2,4]), (False,[1,3]) ]
alphabeticalGroupBy :: (value -> Text, [value]) -> [(Text, [value])] #
alphabeticalGroupBy(key, list)
breaks up the given list
into sublists
that have the same key
.
Neither the order of the elements in each
sublist nor the order of each sublist in the output list is specified,
so you cannot make any assumption about the order in which elements
will be present in the output list.
numericalGroupBy :: (value -> Number, [value]) -> [(Number, [value])] #
numericalGroupBy(key, list)
breaks up the given list
into sublists
that have the same key
.
Neither the order of the elements in each
sublist nor the order of each sublist in the output list is specified,
so you cannot make any assumption about the order in which elements
will be present in the output list.
run :: [value -> value] -> value -> value #
Run a sequence of transformations in order on the given initial state.
For example, the expression run([f1,f2,f3])(x)
is the same as f3(f2(f1(x)))
repeatFor :: (Number, value -> value) -> value -> value #
Repeat a transformation the given number of times.
For example, the expression repeatFor(3,f)(x)
is the same as f(f(f(x)))
.
If you use a negative number or a number with decimals, the sign and
the decimals will be ignored. For example, repeatFor(-7.3,f)
will repeat
7
times.
repeatWhile :: (Predicate value, value -> value) -> value -> value #
Keep repeating a transformation while the given predicate is True. The result is the first value that does not satisfy the predicate.
foreach :: ([input], input -> output) -> [output] #
Constructs a list by applying a function to all the elements of a given list
forloop :: (state, Predicate state, state -> state, state -> output) -> [output] #
Creates the list [a,f(a),f(f(a)),f(f(f(a))),...]
,
where a
is the given value and f
is the given function.
iterated :: ((value -> value), value) -> [value]
iterated(next,input) = input : iterated(next,next input)
forloop(input,cond,next,output)
produces a list of outputs,
where each output is generated by repeatedly applying output
to the current state
, whose value changes after each iteration
of the loop. The state
is initially set to the value given by
input
, and new states are generated from it by applying
next
to the current state
.
The whole process continues for as long as the current state
satisfies the predicate given by cond
.
For example, the following code will produce [0,0,6,6,12,12,20,20]:
forloop(input,cond,next,output) where input = (1,0) cond(n,sum) = n <= 10 next(n,sum) = (n+1,if even(n) then sum+n else sum) output(n,sum) = sum
Using forloop to implement other iteration functions
Basically, any iteration function can be used to implement the rest.
A few examples of implementations based on forloop
follow.
iterated(next,input) = forloop(input,\x -> True,next,pass)
foreach(list,f) = forloop(list,nonEmpty,\l -> rest(l,1),\l -> f(l#1))
repeatWhile(check,f)(v) = last(v:forloop(input,cond,next,output),1)#1 where input = (x,f(x)) cond (x, _) = check(x) next (_,fx) = (fx,f(fx)) output(_,fx) = fx
whileloop :: (state, Predicate state, state -> state, state -> output) -> output #
The function whileloop
works similarly to forloop
, but instead
of collecting outputs of intermediate states, a single output is collected
at the end of the loop. The expression whileloop(input,cond,next,output)
is a shortcode for output(repeatWhile(cond,next)(input))
.
Example 1. The function indexOf
can be implemented as a while loop:
indexOf(x,list) = whileloop(input,cond,next,output) where input = (list,1,0) cond(list,index,found) = nonEmpty(list) && found == 0 next(list,index,found) = ( rest(list,1) , index+1 , if x == list#1 then index else found ) output(list,index,found) = found
Example 2. The average of a list of numbers can be calculated by the following while loop:
average(numbers) = whileloop(input,cond,next,output) where input = (numbers, 0, 0) cond(numbers,_,_) = nonEmpty(numbers) next(numbers,total,quantity) = ( rest(numbers,1) , total + numbers#1 , quantity + 1 ) output(_,_,0) = 0 -- adjust this as needed output(_,total,quantity) = total / quantity
Example 3. The function forloop
can be implemented
in terms of whileloop
:
forloop(input,cond,next,output) = whileloop(input',cond',next',output') where input' = (input,[]) cond'(s,accum) = cond(s) next'(s,accum) = (next(s),prepend(output(s),accum)) output'(s,accum) = reversed(accum)
We could have used append
instead of prepend
, so that the accumulator
does not need to be reversed at the end. However, due to internal
implementation details of CodeWorld, the latter is much more efficient.
listn :: (Number -> value, Number) -> [value] #
Converts a given function f
into a finite
list [f(1),f(2),f(3),...,f(n)]
,
where n
is the given number.
If you use a Number with decimals,
the decimals will be ignored.
butLast :: ([value], Number) -> [value] #
A list containing all the elements of the given list except the
last few. Example: butLast([1,2,3,4],1)
is [1,2,3]
.
pairs :: [value] -> [(value, value)] #
A list of pairs that is created by putting together each consecutive pair of values in the given list. Single elements at the end of the list are discarded.
Example:
pairs([1..9]) -- is [(1,2),(3,4),(5,6),(7,8)]
unpairs :: [(value, value)] -> [value] #
A list of values obtained by flattening the given list of pairs, so that the overall order of the values is preserved.
unzipped :: [(a, b)] -> ([a], [b]) #
A pair of lists obtained by separating each pair from the given list of pairs.
zipped :: ([a], [b]) -> [(a, b)] #
A list of pairs that results from blending the given pair of lists, by taking one value from each list at a time. The resulting list is as short as the shortest of the two given lists. When one of the lists is longer than the other, the extra values will be discarded.
indexOf :: (value, [value]) -> Number #
Either the index of the first occurrence of the given value within the given list, or 0 if the value does not occur in the list. List indices start at 1.
lJustified :: (Text, Number) -> Text #
Justifies text to the left, and adds padding on the right, so that the text occupies exactly the given width. Justification works best with lettering based on monospaced fonts.
rJustified :: (Text, Number) -> Text #
Justifies text to the right, and adds padding on the left, so that the text occupies exactly the given width. Justification works best with lettering based on monospaced fonts.
printedDecimals :: (Number, Number) -> Text #
A text representation of the given number, so that it has exactly the given number of decimals. This means that the output does not represent the given number exactly, but a number that is only approximately equal to the given number. When the number of decimals requested is 1 or more, a decimal point is also included in the text representation, followed or preceded by 0 if necessary.
printedDecimals(7.89,1) -- is "7.9"
printedNumbers :: [Number] -> Text #
A text representation of the given list of numbers.
printedPoint :: Point -> Text #
A text representation of the given point.
letteringBlock :: [Text] -> Picture #
A picture that represents the given list of texts, so that each text in the list is shown in a separate line. Lines start at the top left corner of the output window and grow downward. Each line of text can fit 66 characters, and 40 lines can fit in a single page. The lettering is shown in monospaced font.
cumulativeSums :: [Number] -> [Number] #
A list of cumulative sums calculated from the given list.
cumulativeSums([1,2,3,4]) -- is [1,1+2,1+2+3,1+2+3+4]
Note that cumulativeSums
could be implemented using forloop
as follows:
cumulativeSums(list) = forloop(init,cond,next,output) where init = (list,0) cond = \(list,currentSum) -> nonEmpty(list) next = \(list,currentSum) -> (rest(list,1),currentSum + list#1) output = \(list,currentSum) -> currentSum + list#1
A function that passes the input unchanged as output. It is useful to indicate a transformation that changes nothing for those operations where a transformation is expected.
Creates a number out of a text in such a way that
- it is difficult to predict the number corresponding to a given text, and
- it is relatively unlikely that two similar texts have similar numbers.
drawingOf :: Picture -> Effect #
Show a coordinate plane along with the given Picture. This is intended for debugging purposes, so that you can place your objects more accurately. However, it should not be used for your final product. As a reminder, your picture will fade after 90 seconds.