task_url
stringlengths 30
116
| task_name
stringlengths 2
86
| task_description
stringlengths 0
14.4k
| language_url
stringlengths 2
53
| language_name
stringlengths 1
52
| code
stringlengths 0
61.9k
|
---|---|---|---|---|---|
http://rosettacode.org/wiki/Generate_lower_case_ASCII_alphabet
|
Generate lower case ASCII alphabet
|
Task
Generate an array, list, lazy sequence, or even an indexable string of all the lower case ASCII characters, from a to z. If the standard library contains such a sequence, show how to access it, but don't fail to show how to generate a similar sequence.
For this basic task use a reliable style of coding, a style fit for a very large program, and use strong typing if available. It's bug prone to enumerate all the lowercase characters manually in the code.
During code review it's not immediate obvious to spot the bug in a Tcl line like this contained in a page of code:
set alpha {a b c d e f g h i j k m n o p q r s t u v w x y z}
Other tasks related to string operations:
Metrics
Array length
String length
Copy a string
Empty string (assignment)
Counting
Word frequency
Letter frequency
Jewels and stones
I before E except after C
Bioinformatics/base count
Count occurrences of a substring
Count how many vowels and consonants occur in a string
Remove/replace
XXXX redacted
Conjugate a Latin verb
Remove vowels from a string
String interpolation (included)
Strip block comments
Strip comments from a string
Strip a set of characters from a string
Strip whitespace from a string -- top and tail
Strip control codes and extended characters from a string
Anagrams/Derangements/shuffling
Word wheel
ABC problem
Sattolo cycle
Knuth shuffle
Ordered words
Superpermutation minimisation
Textonyms (using a phone text pad)
Anagrams
Anagrams/Deranged anagrams
Permutations/Derangements
Find/Search/Determine
ABC words
Odd words
Word ladder
Semordnilap
Word search
Wordiff (game)
String matching
Tea cup rim text
Alternade words
Changeable words
State name puzzle
String comparison
Unique characters
Unique characters in each string
Extract file extension
Levenshtein distance
Palindrome detection
Common list elements
Longest common suffix
Longest common prefix
Compare a list of strings
Longest common substring
Find common directory path
Words from neighbour ones
Change e letters to i in words
Non-continuous subsequences
Longest common subsequence
Longest palindromic substrings
Longest increasing subsequence
Words containing "the" substring
Sum of the digits of n is substring of n
Determine if a string is numeric
Determine if a string is collapsible
Determine if a string is squeezable
Determine if a string has all unique characters
Determine if a string has all the same characters
Longest substrings without repeating characters
Find words which contains all the vowels
Find words which contains most consonants
Find words which contains more than 3 vowels
Find words which first and last three letters are equals
Find words which odd letters are consonants and even letters are vowels or vice_versa
Formatting
Substring
Rep-string
Word wrap
String case
Align columns
Literals/String
Repeat a string
Brace expansion
Brace expansion using ranges
Reverse a string
Phrase reversals
Comma quibbling
Special characters
String concatenation
Substring/Top and tail
Commatizing numbers
Reverse words in a string
Suffixation of decimal numbers
Long literals, with continuations
Numerical and alphabetical suffixes
Abbreviations, easy
Abbreviations, simple
Abbreviations, automatic
Song lyrics/poems/Mad Libs/phrases
Mad Libs
Magic 8-ball
99 Bottles of Beer
The Name Game (a song)
The Old lady swallowed a fly
The Twelve Days of Christmas
Tokenize
Text between
Tokenize a string
Word break problem
Tokenize a string with escaping
Split a character string based on change of character
Sequences
Show ASCII table
De Bruijn sequences
Self-referential sequences
Generate lower case ASCII alphabet
|
#Z80_Assembly
|
Z80 Assembly
|
org &8000
ld a,'a' ;data
ld b,26 ;loop counter
ld hl,Alphabet ;destination
loop:
ld (hl),a ;store "a" into ram
inc a ;next letter
inc hl ;next storage byte
djnz loop ;repeat until 26 letters were stored.
call Monitor_MemDump ;hexdumps the specified address and bytecount to screen - created by Keith S. of Chibiakumas
byte 32 ;number of bytes to display
word Alphabet ;address to dump from
ret ;return to basic
Alphabet:
ds 26,0 ;reserve 26 bytes of ram, init all to zero.
|
http://rosettacode.org/wiki/Hello_world/Text
|
Hello world/Text
|
Hello world/Text is part of Short Circuit's Console Program Basics selection.
Task
Display the string Hello world! on a text console.
Related tasks
Hello world/Graphical
Hello world/Line Printer
Hello world/Newbie
Hello world/Newline omission
Hello world/Standard error
Hello world/Web server
|
#R
|
R
|
cat("Hello world!\n")
|
http://rosettacode.org/wiki/Function_composition
|
Function composition
|
Task
Create a function, compose, whose two arguments f and g, are both functions with one argument.
The result of compose is to be a function of one argument, (lets call the argument x), which works like applying function f to the result of applying function g to x.
Example
compose(f, g) (x) = f(g(x))
Reference: Function composition
Hint: In some languages, implementing compose correctly requires creating a closure.
|
#REBOL
|
REBOL
|
rebol [
Title: "Functional Composition"
URL: http://rosettacode.org/wiki/Functional_Composition
]
; "compose" means something else in REBOL, therefore I use a 'compose-functions name.
compose-functions: func [
{compose the given functions F and G}
f [any-function!]
g [any-function!]
] [
func [x] compose [(:f) (:g) x]
]
|
http://rosettacode.org/wiki/Function_composition
|
Function composition
|
Task
Create a function, compose, whose two arguments f and g, are both functions with one argument.
The result of compose is to be a function of one argument, (lets call the argument x), which works like applying function f to the result of applying function g to x.
Example
compose(f, g) (x) = f(g(x))
Reference: Function composition
Hint: In some languages, implementing compose correctly requires creating a closure.
|
#REXX
|
REXX
|
compose: procedure; parse arg f,g,x; interpret 'return' f"(" g'(' x "))"
exit /*control should never gets here, but this was added just in case.*/
|
http://rosettacode.org/wiki/Fractran
|
Fractran
|
FRACTRAN is a Turing-complete esoteric programming language invented by the mathematician John Horton Conway.
A FRACTRAN program is an ordered list of positive fractions
P
=
(
f
1
,
f
2
,
…
,
f
m
)
{\displaystyle P=(f_{1},f_{2},\ldots ,f_{m})}
, together with an initial positive integer input
n
{\displaystyle n}
.
The program is run by updating the integer
n
{\displaystyle n}
as follows:
for the first fraction,
f
i
{\displaystyle f_{i}}
, in the list for which
n
f
i
{\displaystyle nf_{i}}
is an integer, replace
n
{\displaystyle n}
with
n
f
i
{\displaystyle nf_{i}}
;
repeat this rule until no fraction in the list produces an integer when multiplied by
n
{\displaystyle n}
, then halt.
Conway gave a program for primes in FRACTRAN:
17
/
91
{\displaystyle 17/91}
,
78
/
85
{\displaystyle 78/85}
,
19
/
51
{\displaystyle 19/51}
,
23
/
38
{\displaystyle 23/38}
,
29
/
33
{\displaystyle 29/33}
,
77
/
29
{\displaystyle 77/29}
,
95
/
23
{\displaystyle 95/23}
,
77
/
19
{\displaystyle 77/19}
,
1
/
17
{\displaystyle 1/17}
,
11
/
13
{\displaystyle 11/13}
,
13
/
11
{\displaystyle 13/11}
,
15
/
14
{\displaystyle 15/14}
,
15
/
2
{\displaystyle 15/2}
,
55
/
1
{\displaystyle 55/1}
Starting with
n
=
2
{\displaystyle n=2}
, this FRACTRAN program will change
n
{\displaystyle n}
to
15
=
2
×
(
15
/
2
)
{\displaystyle 15=2\times (15/2)}
, then
825
=
15
×
(
55
/
1
)
{\displaystyle 825=15\times (55/1)}
, generating the following sequence of integers:
2
{\displaystyle 2}
,
15
{\displaystyle 15}
,
825
{\displaystyle 825}
,
725
{\displaystyle 725}
,
1925
{\displaystyle 1925}
,
2275
{\displaystyle 2275}
,
425
{\displaystyle 425}
,
390
{\displaystyle 390}
,
330
{\displaystyle 330}
,
290
{\displaystyle 290}
,
770
{\displaystyle 770}
,
…
{\displaystyle \ldots }
After 2, this sequence contains the following powers of 2:
2
2
=
4
{\displaystyle 2^{2}=4}
,
2
3
=
8
{\displaystyle 2^{3}=8}
,
2
5
=
32
{\displaystyle 2^{5}=32}
,
2
7
=
128
{\displaystyle 2^{7}=128}
,
2
11
=
2048
{\displaystyle 2^{11}=2048}
,
2
13
=
8192
{\displaystyle 2^{13}=8192}
,
2
17
=
131072
{\displaystyle 2^{17}=131072}
,
2
19
=
524288
{\displaystyle 2^{19}=524288}
,
…
{\displaystyle \ldots }
which are the prime powers of 2.
Task
Write a program that reads a list of fractions in a natural format from the keyboard or from a string,
to parse it into a sequence of fractions (i.e. two integers),
and runs the FRACTRAN starting from a provided integer, writing the result at each step.
It is also required that the number of steps is limited (by a parameter easy to find).
Extra credit
Use this program to derive the first 20 or so prime numbers.
See also
For more on how to program FRACTRAN as a universal programming language, see:
J. H. Conway (1987). Fractran: A Simple Universal Programming Language for Arithmetic. In: Open Problems in Communication and Computation, pages 4–26. Springer.
J. H. Conway (2010). "FRACTRAN: A simple universal programming language for arithmetic". In Jeffrey C. Lagarias. The Ultimate Challenge: the 3x+1 problem. American Mathematical Society. pp. 249–264. ISBN 978-0-8218-4940-8. Zbl 1216.68068.
Number Pathology: Fractran by Mark C. Chu-Carroll; October 27, 2006.
|
#Wren
|
Wren
|
import "/big" for BigInt, BigRat
var isPowerOfTwo = Fn.new { |bi| bi & (bi - BigInt.one) == BigInt.zero }
var fractran = Fn.new { |program, n, limit, primesOnly|
var fractions = program.split(" ").where { |s| s != "" }
.map { |s| BigRat.fromRationalString(s) }
.toList
var results = []
if (!primesOnly) results.add(n)
var nn = BigInt.new(n)
while (results.count < limit) {
var fracs = fractions.where { |f| (f * nn).isInteger }.toList
if (fracs.count == 0) break
var frac = fracs[0]
nn = nn * frac.num / frac.den
if (!primesOnly) {
results.add(nn.toSmall)
} else if (primesOnly && isPowerOfTwo.call(nn)) {
var prime = (nn.toNum.log / 2.log).floor
results.add(prime)
}
}
return results
}
var program = "17/91 78/85 19/51 23/38 29/33 77/29 95/23 77/19 1/17 11/13 13/11 15/14 15/2 55/1"
System.print("First twenty numbers:")
System.print(fractran.call(program, 2, 20, false))
System.print("\nFirst ten primes:")
System.print(fractran.call(program, 2, 10, true))
|
http://rosettacode.org/wiki/Function_definition
|
Function definition
|
A function is a body of code that returns a value.
The value returned may depend on arguments provided to the function.
Task
Write a definition of a function called "multiply" that takes two arguments and returns their product.
(Argument types should be chosen so as not to distract from showing how functions are created and values returned).
Related task
Function prototype
|
#dc
|
dc
|
[*] sm
|
http://rosettacode.org/wiki/Gamma_function
|
Gamma function
|
Task
Implement one algorithm (or more) to compute the Gamma (
Γ
{\displaystyle \Gamma }
) function (in the real field only).
If your language has the function as built-in or you know a library which has it, compare your implementation's results with the results of the built-in/library function.
The Gamma function can be defined as:
Γ
(
x
)
=
∫
0
∞
t
x
−
1
e
−
t
d
t
{\displaystyle \Gamma (x)=\displaystyle \int _{0}^{\infty }t^{x-1}e^{-t}dt}
This suggests a straightforward (but inefficient) way of computing the
Γ
{\displaystyle \Gamma }
through numerical integration.
Better suggested methods:
Lanczos approximation
Stirling's approximation
|
#Stata
|
Stata
|
mata
_gamma_coef = 1.0,
5.772156649015328606065121e-1,
-6.558780715202538810770195e-1,
-4.200263503409523552900393e-2,
1.665386113822914895017008e-1,
-4.219773455554433674820830e-2,
-9.621971527876973562114922e-3,
7.218943246663099542395010e-3,
-1.165167591859065112113971e-3,
-2.152416741149509728157300e-4,
1.280502823881161861531986e-4,
-2.013485478078823865568939e-5,
-1.250493482142670657345359e-6,
1.133027231981695882374130e-6,
-2.056338416977607103450154e-7,
6.116095104481415817862499e-9,
5.002007644469222930055665e-9,
-1.181274570487020144588127e-9,
1.04342671169110051049154e-10,
7.782263439905071254049937e-12,
-3.696805618642205708187816e-12,
5.100370287454475979015481e-13,
-2.05832605356650678322243e-14,
-5.348122539423017982370017e-15,
1.226778628238260790158894e-15,
-1.181259301697458769513765e-16,
1.186692254751600332579777e-18,
1.412380655318031781555804e-18,
-2.298745684435370206592479e-19,
1.714406321927337433383963e-20
function gamma_(x_) {
external _gamma_coef
x = x_
y = 1
while (x<0.5) y = y/x++
while (x>1.5) y = --x*y
z = _gamma_coef[30]
x--
for (i=29; i>=1; i--) z = z*x+_gamma_coef[i]
return(y/z)
}
function map(f,a) {
n = rows(a)
p = cols(a)
b = J(n,p,.)
for (i=1; i<=n; i++) {
for (j=1; j<=p; j++) {
b[i,j] = (*f)(a[i,j])
}
}
return(b)
}
x=(1::1000)/100
u=map(&gamma(),x)
v=map(&gamma_(),x)
max(abs((v-u):/u))
end
|
http://rosettacode.org/wiki/Gamma_function
|
Gamma function
|
Task
Implement one algorithm (or more) to compute the Gamma (
Γ
{\displaystyle \Gamma }
) function (in the real field only).
If your language has the function as built-in or you know a library which has it, compare your implementation's results with the results of the built-in/library function.
The Gamma function can be defined as:
Γ
(
x
)
=
∫
0
∞
t
x
−
1
e
−
t
d
t
{\displaystyle \Gamma (x)=\displaystyle \int _{0}^{\infty }t^{x-1}e^{-t}dt}
This suggests a straightforward (but inefficient) way of computing the
Γ
{\displaystyle \Gamma }
through numerical integration.
Better suggested methods:
Lanczos approximation
Stirling's approximation
|
#Tcl
|
Tcl
|
package require math
package require math::calculus
# gamma(1) and gamma(1.5)
set f 1.0
set f2 [expr {sqrt(acos(-1.))/2.}]
for {set x 1.0} {$x <= 10.0} {set x [expr {$x + 0.5}]} {
# method 1 - numerical integration, Romberg's method, special
# case for an improper integral
set g1 [math::calculus::romberg \
[list apply {{x t} {expr {$t ** ($x-1) * exp(-$t)}}} $x] \
0 1 -relerror 1e-8]
set g2 [math::calculus::romberg_infinity \
[list apply {{x t} {expr {$t ** ($x-1) * exp(-$t)}}} $x] \
1 Inf -relerror 1e-8]
set gamma [expr {[lindex $g1 0] + [lindex $g2 0]}]
# method 2 - library function
set libgamma [expr {exp([math::ln_Gamma $x])}]
# method 3 - special forms for integer and half-integer arguments
if {$x == entier($x)} {
puts [format {%4.1f %13.6f %13.6f %13.6f} $x $gamma $libgamma $f]
set f [expr $f * $x]
} else {
puts [format {%4.1f %13.6f %13.6f %13.6f} $x $gamma $libgamma $f2]
set f2 [expr $f2 * $x]
}
}
|
http://rosettacode.org/wiki/Generate_lower_case_ASCII_alphabet
|
Generate lower case ASCII alphabet
|
Task
Generate an array, list, lazy sequence, or even an indexable string of all the lower case ASCII characters, from a to z. If the standard library contains such a sequence, show how to access it, but don't fail to show how to generate a similar sequence.
For this basic task use a reliable style of coding, a style fit for a very large program, and use strong typing if available. It's bug prone to enumerate all the lowercase characters manually in the code.
During code review it's not immediate obvious to spot the bug in a Tcl line like this contained in a page of code:
set alpha {a b c d e f g h i j k m n o p q r s t u v w x y z}
Other tasks related to string operations:
Metrics
Array length
String length
Copy a string
Empty string (assignment)
Counting
Word frequency
Letter frequency
Jewels and stones
I before E except after C
Bioinformatics/base count
Count occurrences of a substring
Count how many vowels and consonants occur in a string
Remove/replace
XXXX redacted
Conjugate a Latin verb
Remove vowels from a string
String interpolation (included)
Strip block comments
Strip comments from a string
Strip a set of characters from a string
Strip whitespace from a string -- top and tail
Strip control codes and extended characters from a string
Anagrams/Derangements/shuffling
Word wheel
ABC problem
Sattolo cycle
Knuth shuffle
Ordered words
Superpermutation minimisation
Textonyms (using a phone text pad)
Anagrams
Anagrams/Deranged anagrams
Permutations/Derangements
Find/Search/Determine
ABC words
Odd words
Word ladder
Semordnilap
Word search
Wordiff (game)
String matching
Tea cup rim text
Alternade words
Changeable words
State name puzzle
String comparison
Unique characters
Unique characters in each string
Extract file extension
Levenshtein distance
Palindrome detection
Common list elements
Longest common suffix
Longest common prefix
Compare a list of strings
Longest common substring
Find common directory path
Words from neighbour ones
Change e letters to i in words
Non-continuous subsequences
Longest common subsequence
Longest palindromic substrings
Longest increasing subsequence
Words containing "the" substring
Sum of the digits of n is substring of n
Determine if a string is numeric
Determine if a string is collapsible
Determine if a string is squeezable
Determine if a string has all unique characters
Determine if a string has all the same characters
Longest substrings without repeating characters
Find words which contains all the vowels
Find words which contains most consonants
Find words which contains more than 3 vowels
Find words which first and last three letters are equals
Find words which odd letters are consonants and even letters are vowels or vice_versa
Formatting
Substring
Rep-string
Word wrap
String case
Align columns
Literals/String
Repeat a string
Brace expansion
Brace expansion using ranges
Reverse a string
Phrase reversals
Comma quibbling
Special characters
String concatenation
Substring/Top and tail
Commatizing numbers
Reverse words in a string
Suffixation of decimal numbers
Long literals, with continuations
Numerical and alphabetical suffixes
Abbreviations, easy
Abbreviations, simple
Abbreviations, automatic
Song lyrics/poems/Mad Libs/phrases
Mad Libs
Magic 8-ball
99 Bottles of Beer
The Name Game (a song)
The Old lady swallowed a fly
The Twelve Days of Christmas
Tokenize
Text between
Tokenize a string
Word break problem
Tokenize a string with escaping
Split a character string based on change of character
Sequences
Show ASCII table
De Bruijn sequences
Self-referential sequences
Generate lower case ASCII alphabet
|
#zkl
|
zkl
|
["a".."z"] // lasy list
["a".."z"].walk() //-->L("a","b","c","d","e",...
"a".toAsc().pump(26,List,"toChar") // another way to create the list
"a".toAsc().pump(26,String,"toChar") // create a string
//-->"abcdefghijklmnopqrstuvwxyz"
Utils.Helpers.lowerLetters // string const
|
http://rosettacode.org/wiki/Generate_lower_case_ASCII_alphabet
|
Generate lower case ASCII alphabet
|
Task
Generate an array, list, lazy sequence, or even an indexable string of all the lower case ASCII characters, from a to z. If the standard library contains such a sequence, show how to access it, but don't fail to show how to generate a similar sequence.
For this basic task use a reliable style of coding, a style fit for a very large program, and use strong typing if available. It's bug prone to enumerate all the lowercase characters manually in the code.
During code review it's not immediate obvious to spot the bug in a Tcl line like this contained in a page of code:
set alpha {a b c d e f g h i j k m n o p q r s t u v w x y z}
Other tasks related to string operations:
Metrics
Array length
String length
Copy a string
Empty string (assignment)
Counting
Word frequency
Letter frequency
Jewels and stones
I before E except after C
Bioinformatics/base count
Count occurrences of a substring
Count how many vowels and consonants occur in a string
Remove/replace
XXXX redacted
Conjugate a Latin verb
Remove vowels from a string
String interpolation (included)
Strip block comments
Strip comments from a string
Strip a set of characters from a string
Strip whitespace from a string -- top and tail
Strip control codes and extended characters from a string
Anagrams/Derangements/shuffling
Word wheel
ABC problem
Sattolo cycle
Knuth shuffle
Ordered words
Superpermutation minimisation
Textonyms (using a phone text pad)
Anagrams
Anagrams/Deranged anagrams
Permutations/Derangements
Find/Search/Determine
ABC words
Odd words
Word ladder
Semordnilap
Word search
Wordiff (game)
String matching
Tea cup rim text
Alternade words
Changeable words
State name puzzle
String comparison
Unique characters
Unique characters in each string
Extract file extension
Levenshtein distance
Palindrome detection
Common list elements
Longest common suffix
Longest common prefix
Compare a list of strings
Longest common substring
Find common directory path
Words from neighbour ones
Change e letters to i in words
Non-continuous subsequences
Longest common subsequence
Longest palindromic substrings
Longest increasing subsequence
Words containing "the" substring
Sum of the digits of n is substring of n
Determine if a string is numeric
Determine if a string is collapsible
Determine if a string is squeezable
Determine if a string has all unique characters
Determine if a string has all the same characters
Longest substrings without repeating characters
Find words which contains all the vowels
Find words which contains most consonants
Find words which contains more than 3 vowels
Find words which first and last three letters are equals
Find words which odd letters are consonants and even letters are vowels or vice_versa
Formatting
Substring
Rep-string
Word wrap
String case
Align columns
Literals/String
Repeat a string
Brace expansion
Brace expansion using ranges
Reverse a string
Phrase reversals
Comma quibbling
Special characters
String concatenation
Substring/Top and tail
Commatizing numbers
Reverse words in a string
Suffixation of decimal numbers
Long literals, with continuations
Numerical and alphabetical suffixes
Abbreviations, easy
Abbreviations, simple
Abbreviations, automatic
Song lyrics/poems/Mad Libs/phrases
Mad Libs
Magic 8-ball
99 Bottles of Beer
The Name Game (a song)
The Old lady swallowed a fly
The Twelve Days of Christmas
Tokenize
Text between
Tokenize a string
Word break problem
Tokenize a string with escaping
Split a character string based on change of character
Sequences
Show ASCII table
De Bruijn sequences
Self-referential sequences
Generate lower case ASCII alphabet
|
#Zig
|
Zig
|
const std = @import("std");
pub fn main() !void {
const cnt_lower = 26;
var lower: [cnt_lower]u8 = undefined;
comptime var i = 0;
inline while (i < cnt_lower) : (i += 1)
lower[i] = i + 'a';
const stdout_wr = std.io.getStdOut().writer();
for (lower) |l|
try stdout_wr.print("{c} ", .{l});
try stdout_wr.writeByte('\n');
}
|
http://rosettacode.org/wiki/Hello_world/Text
|
Hello world/Text
|
Hello world/Text is part of Short Circuit's Console Program Basics selection.
Task
Display the string Hello world! on a text console.
Related tasks
Hello world/Graphical
Hello world/Line Printer
Hello world/Newbie
Hello world/Newline omission
Hello world/Standard error
Hello world/Web server
|
#Ra
|
Ra
|
class HelloWorld
**Prints "Hello world!"**
on start
print "Hello world!"
|
http://rosettacode.org/wiki/Function_composition
|
Function composition
|
Task
Create a function, compose, whose two arguments f and g, are both functions with one argument.
The result of compose is to be a function of one argument, (lets call the argument x), which works like applying function f to the result of applying function g to x.
Example
compose(f, g) (x) = f(g(x))
Reference: Function composition
Hint: In some languages, implementing compose correctly requires creating a closure.
|
#Ring
|
Ring
|
# Project : Function composition
sumprod = func1(:func2,2,3)
see sumprod + nl
func func1(func2,x,y)
temp = call func2(x,y)
res = temp + x + y
return res
func func2(x,y)
res = x * y
return res
|
http://rosettacode.org/wiki/Function_composition
|
Function composition
|
Task
Create a function, compose, whose two arguments f and g, are both functions with one argument.
The result of compose is to be a function of one argument, (lets call the argument x), which works like applying function f to the result of applying function g to x.
Example
compose(f, g) (x) = f(g(x))
Reference: Function composition
Hint: In some languages, implementing compose correctly requires creating a closure.
|
#Ruby
|
Ruby
|
def compose(f,g)
lambda {|x| f[g[x]]}
end
s = compose(Math.method(:sin), Math.method(:cos))
p s[0.5] # => 0.769196354841008
# verify
p Math.sin(Math.cos(0.5)) # => 0.769196354841008
|
http://rosettacode.org/wiki/Fractran
|
Fractran
|
FRACTRAN is a Turing-complete esoteric programming language invented by the mathematician John Horton Conway.
A FRACTRAN program is an ordered list of positive fractions
P
=
(
f
1
,
f
2
,
…
,
f
m
)
{\displaystyle P=(f_{1},f_{2},\ldots ,f_{m})}
, together with an initial positive integer input
n
{\displaystyle n}
.
The program is run by updating the integer
n
{\displaystyle n}
as follows:
for the first fraction,
f
i
{\displaystyle f_{i}}
, in the list for which
n
f
i
{\displaystyle nf_{i}}
is an integer, replace
n
{\displaystyle n}
with
n
f
i
{\displaystyle nf_{i}}
;
repeat this rule until no fraction in the list produces an integer when multiplied by
n
{\displaystyle n}
, then halt.
Conway gave a program for primes in FRACTRAN:
17
/
91
{\displaystyle 17/91}
,
78
/
85
{\displaystyle 78/85}
,
19
/
51
{\displaystyle 19/51}
,
23
/
38
{\displaystyle 23/38}
,
29
/
33
{\displaystyle 29/33}
,
77
/
29
{\displaystyle 77/29}
,
95
/
23
{\displaystyle 95/23}
,
77
/
19
{\displaystyle 77/19}
,
1
/
17
{\displaystyle 1/17}
,
11
/
13
{\displaystyle 11/13}
,
13
/
11
{\displaystyle 13/11}
,
15
/
14
{\displaystyle 15/14}
,
15
/
2
{\displaystyle 15/2}
,
55
/
1
{\displaystyle 55/1}
Starting with
n
=
2
{\displaystyle n=2}
, this FRACTRAN program will change
n
{\displaystyle n}
to
15
=
2
×
(
15
/
2
)
{\displaystyle 15=2\times (15/2)}
, then
825
=
15
×
(
55
/
1
)
{\displaystyle 825=15\times (55/1)}
, generating the following sequence of integers:
2
{\displaystyle 2}
,
15
{\displaystyle 15}
,
825
{\displaystyle 825}
,
725
{\displaystyle 725}
,
1925
{\displaystyle 1925}
,
2275
{\displaystyle 2275}
,
425
{\displaystyle 425}
,
390
{\displaystyle 390}
,
330
{\displaystyle 330}
,
290
{\displaystyle 290}
,
770
{\displaystyle 770}
,
…
{\displaystyle \ldots }
After 2, this sequence contains the following powers of 2:
2
2
=
4
{\displaystyle 2^{2}=4}
,
2
3
=
8
{\displaystyle 2^{3}=8}
,
2
5
=
32
{\displaystyle 2^{5}=32}
,
2
7
=
128
{\displaystyle 2^{7}=128}
,
2
11
=
2048
{\displaystyle 2^{11}=2048}
,
2
13
=
8192
{\displaystyle 2^{13}=8192}
,
2
17
=
131072
{\displaystyle 2^{17}=131072}
,
2
19
=
524288
{\displaystyle 2^{19}=524288}
,
…
{\displaystyle \ldots }
which are the prime powers of 2.
Task
Write a program that reads a list of fractions in a natural format from the keyboard or from a string,
to parse it into a sequence of fractions (i.e. two integers),
and runs the FRACTRAN starting from a provided integer, writing the result at each step.
It is also required that the number of steps is limited (by a parameter easy to find).
Extra credit
Use this program to derive the first 20 or so prime numbers.
See also
For more on how to program FRACTRAN as a universal programming language, see:
J. H. Conway (1987). Fractran: A Simple Universal Programming Language for Arithmetic. In: Open Problems in Communication and Computation, pages 4–26. Springer.
J. H. Conway (2010). "FRACTRAN: A simple universal programming language for arithmetic". In Jeffrey C. Lagarias. The Ultimate Challenge: the 3x+1 problem. American Mathematical Society. pp. 249–264. ISBN 978-0-8218-4940-8. Zbl 1216.68068.
Number Pathology: Fractran by Mark C. Chu-Carroll; October 27, 2006.
|
#zkl
|
zkl
|
var fracs="17/91, 78/85, 19/51, 23/38, 29/33, 77/29, 95/23, 77/19, 1/17,"
"11/13, 13/11, 15/14, 15/2, 55/1";
fcn fractranW(n,fracsAsOneBigString){ //-->Walker (iterator)
fracs:=(fracsAsOneBigString-" ").split(",").apply(
fcn(frac){ frac.split("/").apply("toInt") }); //( (n,d), (n,d), ...)
Walker(fcn(rn,fracs){
n:=rn.value;
foreach a,b in (fracs){
if(n*a%b == 0){
rn.set(n*a/b);
return(n);
}
}
}.fp(Ref(n),fracs))
}
|
http://rosettacode.org/wiki/Function_definition
|
Function definition
|
A function is a body of code that returns a value.
The value returned may depend on arguments provided to the function.
Task
Write a definition of a function called "multiply" that takes two arguments and returns their product.
(Argument types should be chosen so as not to distract from showing how functions are created and values returned).
Related task
Function prototype
|
#Delphi
|
Delphi
|
function multiply(a, b: integer): integer;
begin
result := a * b;
end;
|
http://rosettacode.org/wiki/Gamma_function
|
Gamma function
|
Task
Implement one algorithm (or more) to compute the Gamma (
Γ
{\displaystyle \Gamma }
) function (in the real field only).
If your language has the function as built-in or you know a library which has it, compare your implementation's results with the results of the built-in/library function.
The Gamma function can be defined as:
Γ
(
x
)
=
∫
0
∞
t
x
−
1
e
−
t
d
t
{\displaystyle \Gamma (x)=\displaystyle \int _{0}^{\infty }t^{x-1}e^{-t}dt}
This suggests a straightforward (but inefficient) way of computing the
Γ
{\displaystyle \Gamma }
through numerical integration.
Better suggested methods:
Lanczos approximation
Stirling's approximation
|
#TI-83_BASIC
|
TI-83 BASIC
|
.5! -> .8862269255
|
http://rosettacode.org/wiki/Hello_world/Text
|
Hello world/Text
|
Hello world/Text is part of Short Circuit's Console Program Basics selection.
Task
Display the string Hello world! on a text console.
Related tasks
Hello world/Graphical
Hello world/Line Printer
Hello world/Newbie
Hello world/Newline omission
Hello world/Standard error
Hello world/Web server
|
#Racket
|
Racket
|
(printf "Hello world!\n")
|
http://rosettacode.org/wiki/Function_composition
|
Function composition
|
Task
Create a function, compose, whose two arguments f and g, are both functions with one argument.
The result of compose is to be a function of one argument, (lets call the argument x), which works like applying function f to the result of applying function g to x.
Example
compose(f, g) (x) = f(g(x))
Reference: Function composition
Hint: In some languages, implementing compose correctly requires creating a closure.
|
#Rust
|
Rust
|
fn compose<'a,F,G,T,U,V>(f: F, g: G) -> Box<Fn(T) -> V + 'a>
where F: Fn(U) -> V + 'a,
G: Fn(T) -> U + 'a,
{
Box::new(move |x| f(g(x)))
}
|
http://rosettacode.org/wiki/Function_composition
|
Function composition
|
Task
Create a function, compose, whose two arguments f and g, are both functions with one argument.
The result of compose is to be a function of one argument, (lets call the argument x), which works like applying function f to the result of applying function g to x.
Example
compose(f, g) (x) = f(g(x))
Reference: Function composition
Hint: In some languages, implementing compose correctly requires creating a closure.
|
#Scala
|
Scala
|
def compose[A](f: A => A, g: A => A) = { x: A => f(g(x)) }
def add1(x: Int) = x+1
val add2 = compose(add1, add1)
|
http://rosettacode.org/wiki/Function_definition
|
Function definition
|
A function is a body of code that returns a value.
The value returned may depend on arguments provided to the function.
Task
Write a definition of a function called "multiply" that takes two arguments and returns their product.
(Argument types should be chosen so as not to distract from showing how functions are created and values returned).
Related task
Function prototype
|
#Diego
|
Diego
|
begin_funct({number}, multiply)_param({number}, a, b);
with_funct[]_calc([a]*[b]);
end_funct[];
me_msg()_funct(multiply)_param(1,2);
|
http://rosettacode.org/wiki/Gamma_function
|
Gamma function
|
Task
Implement one algorithm (or more) to compute the Gamma (
Γ
{\displaystyle \Gamma }
) function (in the real field only).
If your language has the function as built-in or you know a library which has it, compare your implementation's results with the results of the built-in/library function.
The Gamma function can be defined as:
Γ
(
x
)
=
∫
0
∞
t
x
−
1
e
−
t
d
t
{\displaystyle \Gamma (x)=\displaystyle \int _{0}^{\infty }t^{x-1}e^{-t}dt}
This suggests a straightforward (but inefficient) way of computing the
Γ
{\displaystyle \Gamma }
through numerical integration.
Better suggested methods:
Lanczos approximation
Stirling's approximation
|
#Visual_FoxPro
|
Visual FoxPro
|
LOCAL i As Integer, x As Double, o As lanczos
CLOSE DATABASES ALL
CLEAR
CREATE CURSOR results (ZVal B(1), GamVal B(15))
INDEX ON zval TAG ZVal COLLATE "Machine"
SET ORDER TO 0
o = CREATEOBJECT("lanczos")
FOR i = 1 TO 20
x = i/10
INSERT INTO results VALUES (x, o.Gamma(x))
ENDFOR
UPDATE results SET GamVal = ROUND(GamVal, 0) WHERE ZVal = INT(ZVal)
*!* This just creates the output text - it is not part of the algorithm
DO cursor2txt.prg WITH "results", .T.
DEFINE CLASS lanczos As Session
#DEFINE FPF 5.5
#DEFINE HALF 0.5
#DEFINE PY PI()
DIMENSION LanCoeff[7]
nSize = 0
PROCEDURE Init
DODEFAULT()
WITH THIS
.LanCoeff[1] = 1.000000000190015
.LanCoeff[2] = 76.18009172947146
.LanCoeff[3] = -86.50532032941677
.LanCoeff[4] = 24.01409824083091
.LanCoeff[5] = -1.231739572450155
.LanCoeff[6] = 0.0012086509738662
.LanCoeff[7] = -0.000005395239385
.nSize = ALEN(.LanCoeff)
ENDWITH
ENDPROC
FUNCTION Gamma(z)
RETURN EXP(THIS.LogGamma(z))
ENDFUNC
FUNCTION LogGamma(z)
LOCAL a As Double, b As Double, i As Integer, j As Integer, lg As Double
IF z < 0.5
lg = LOG(PY/SIN(PY*z)) - THIS.LogGamma(1 - z)
ELSE
WITH THIS
z = z - 1
b = z + FPF
a = .LanCoeff[1]
FOR i = 2 TO .nSize
j = i - 1
a = a + .LanCoeff[i]/(z + j)
ENDFOR
lg = (LOG(SQRT(2*PY)) + LOG(a) - b) + LOG(b)*(z + HALF)
ENDWITH
ENDIF
RETURN lg
ENDFUNC
ENDDEFINE
|
http://rosettacode.org/wiki/Gamma_function
|
Gamma function
|
Task
Implement one algorithm (or more) to compute the Gamma (
Γ
{\displaystyle \Gamma }
) function (in the real field only).
If your language has the function as built-in or you know a library which has it, compare your implementation's results with the results of the built-in/library function.
The Gamma function can be defined as:
Γ
(
x
)
=
∫
0
∞
t
x
−
1
e
−
t
d
t
{\displaystyle \Gamma (x)=\displaystyle \int _{0}^{\infty }t^{x-1}e^{-t}dt}
This suggests a straightforward (but inefficient) way of computing the
Γ
{\displaystyle \Gamma }
through numerical integration.
Better suggested methods:
Lanczos approximation
Stirling's approximation
|
#Vlang
|
Vlang
|
import math
fn main() {
println(" x math.Gamma Lanczos7")
for x in [-.5, .1, .5, 1, 1.5, 2, 3, 10, 140, 170] {
println("${x:5.1f} ${math.gamma(x):24.16} ${lanczos7(x):24.16}")
}
}
fn lanczos7(z f64) f64 {
t := z + 6.5
x := .99999999999980993 +
676.5203681218851/z -
1259.1392167224028/(z+1) +
771.32342877765313/(z+2) -
176.61502916214059/(z+3) +
12.507343278686905/(z+4) -
.13857109526572012/(z+5) +
9.9843695780195716e-6/(z+6) +
1.5056327351493116e-7/(z+7)
return math.sqrt2 * math.sqrt_pi * math.pow(t, z-.5) * math.exp(-t) * x
}
|
http://rosettacode.org/wiki/Hello_world/Text
|
Hello world/Text
|
Hello world/Text is part of Short Circuit's Console Program Basics selection.
Task
Display the string Hello world! on a text console.
Related tasks
Hello world/Graphical
Hello world/Line Printer
Hello world/Newbie
Hello world/Newline omission
Hello world/Standard error
Hello world/Web server
|
#Raku
|
Raku
|
say 'Hello world!';
|
http://rosettacode.org/wiki/Function_composition
|
Function composition
|
Task
Create a function, compose, whose two arguments f and g, are both functions with one argument.
The result of compose is to be a function of one argument, (lets call the argument x), which works like applying function f to the result of applying function g to x.
Example
compose(f, g) (x) = f(g(x))
Reference: Function composition
Hint: In some languages, implementing compose correctly requires creating a closure.
|
#Scheme
|
Scheme
|
(define (compose f g) (lambda (x) (f (g x))))
;; or:
(define ((compose f g) x) (f (g x)))
;; or to compose an arbitrary list of 1 argument functions:
(define-syntax compose
(lambda (x)
(syntax-case x ()
((_) #'(lambda (y) y))
((_ f) #'f)
((_ f g h ...) #'(lambda (y) (f ((compose g h ...) y)))))))
|
http://rosettacode.org/wiki/Function_composition
|
Function composition
|
Task
Create a function, compose, whose two arguments f and g, are both functions with one argument.
The result of compose is to be a function of one argument, (lets call the argument x), which works like applying function f to the result of applying function g to x.
Example
compose(f, g) (x) = f(g(x))
Reference: Function composition
Hint: In some languages, implementing compose correctly requires creating a closure.
|
#Sidef
|
Sidef
|
func compose(f, g) {
func(x) { f(g(x)) }
}
var fg = compose(func(x){ sin(x) }, func(x){ cos(x) })
say fg(0.5) # => 0.76919635484100842185251475805107
|
http://rosettacode.org/wiki/Function_definition
|
Function definition
|
A function is a body of code that returns a value.
The value returned may depend on arguments provided to the function.
Task
Write a definition of a function called "multiply" that takes two arguments and returns their product.
(Argument types should be chosen so as not to distract from showing how functions are created and values returned).
Related task
Function prototype
|
#Draco
|
Draco
|
proc multiply(word a, b) word:
a * b
corp
|
http://rosettacode.org/wiki/Gamma_function
|
Gamma function
|
Task
Implement one algorithm (or more) to compute the Gamma (
Γ
{\displaystyle \Gamma }
) function (in the real field only).
If your language has the function as built-in or you know a library which has it, compare your implementation's results with the results of the built-in/library function.
The Gamma function can be defined as:
Γ
(
x
)
=
∫
0
∞
t
x
−
1
e
−
t
d
t
{\displaystyle \Gamma (x)=\displaystyle \int _{0}^{\infty }t^{x-1}e^{-t}dt}
This suggests a straightforward (but inefficient) way of computing the
Γ
{\displaystyle \Gamma }
through numerical integration.
Better suggested methods:
Lanczos approximation
Stirling's approximation
|
#Wren
|
Wren
|
import "/fmt" for Fmt
import "/math" for Math
var stirling = Fn.new { |x| (2 * Num.pi / x).sqrt * (x / Math.e).pow(x) }
System.print(" x\tStirling\t\tLanczos\n")
for (i in 1..20) {
var d = i / 10
System.write("%(Fmt.f(4, d, 2))\t")
System.write("%(Fmt.f(16, stirling.call(d), 14))\t")
System.print("%(Fmt.f(16, Math.gamma(d), 14))")
}
|
http://rosettacode.org/wiki/Hello_world/Text
|
Hello world/Text
|
Hello world/Text is part of Short Circuit's Console Program Basics selection.
Task
Display the string Hello world! on a text console.
Related tasks
Hello world/Graphical
Hello world/Line Printer
Hello world/Newbie
Hello world/Newline omission
Hello world/Standard error
Hello world/Web server
|
#Raven
|
Raven
|
'Hello world!' print
|
http://rosettacode.org/wiki/Function_composition
|
Function composition
|
Task
Create a function, compose, whose two arguments f and g, are both functions with one argument.
The result of compose is to be a function of one argument, (lets call the argument x), which works like applying function f to the result of applying function g to x.
Example
compose(f, g) (x) = f(g(x))
Reference: Function composition
Hint: In some languages, implementing compose correctly requires creating a closure.
|
#Slate
|
Slate
|
[| :x | x + 1] ** [| :x | x squared] applyTo: {3}
|
http://rosettacode.org/wiki/Function_composition
|
Function composition
|
Task
Create a function, compose, whose two arguments f and g, are both functions with one argument.
The result of compose is to be a function of one argument, (lets call the argument x), which works like applying function f to the result of applying function g to x.
Example
compose(f, g) (x) = f(g(x))
Reference: Function composition
Hint: In some languages, implementing compose correctly requires creating a closure.
|
#Smalltalk
|
Smalltalk
|
| composer fg |
composer := [ :f :g | [ :x | f value: (g value: x) ] ].
fg := composer value: [ :x | x + 1 ]
value: [ :x | x * x ].
(fg value:3) displayNl.
|
http://rosettacode.org/wiki/Function_definition
|
Function definition
|
A function is a body of code that returns a value.
The value returned may depend on arguments provided to the function.
Task
Write a definition of a function called "multiply" that takes two arguments and returns their product.
(Argument types should be chosen so as not to distract from showing how functions are created and values returned).
Related task
Function prototype
|
#Dragon
|
Dragon
|
func multiply(a, b) {
return a*b
}
|
http://rosettacode.org/wiki/Gamma_function
|
Gamma function
|
Task
Implement one algorithm (or more) to compute the Gamma (
Γ
{\displaystyle \Gamma }
) function (in the real field only).
If your language has the function as built-in or you know a library which has it, compare your implementation's results with the results of the built-in/library function.
The Gamma function can be defined as:
Γ
(
x
)
=
∫
0
∞
t
x
−
1
e
−
t
d
t
{\displaystyle \Gamma (x)=\displaystyle \int _{0}^{\infty }t^{x-1}e^{-t}dt}
This suggests a straightforward (but inefficient) way of computing the
Γ
{\displaystyle \Gamma }
through numerical integration.
Better suggested methods:
Lanczos approximation
Stirling's approximation
|
#Yabasic
|
Yabasic
|
dim c(12)
sub gamma(z)
local accm, k, k1_factrl
accm = c(1)
if accm=0 then
accm = sqrt(2*PI)
c(1) = accm
k1_factrl = 1
for k=2 to 12
c(k) = exp(13-k)*(13-k)^(k-1.5)/k1_factrl
k1_factrl = k1_factrl * -(k-1)
next
end if
for k=2 to 12
accm = accm + c(k)/(z+k-1)
next
accm = accm * exp(-(z+12))*(z+12)^(z+0.5)
return accm/z
end sub
sub si(x)
print x using "%18.13f"
end sub
for i = 0.1 to 2.1 step .1
print i, " = "; : si(gamma(i))
next
|
http://rosettacode.org/wiki/Gamma_function
|
Gamma function
|
Task
Implement one algorithm (or more) to compute the Gamma (
Γ
{\displaystyle \Gamma }
) function (in the real field only).
If your language has the function as built-in or you know a library which has it, compare your implementation's results with the results of the built-in/library function.
The Gamma function can be defined as:
Γ
(
x
)
=
∫
0
∞
t
x
−
1
e
−
t
d
t
{\displaystyle \Gamma (x)=\displaystyle \int _{0}^{\infty }t^{x-1}e^{-t}dt}
This suggests a straightforward (but inefficient) way of computing the
Γ
{\displaystyle \Gamma }
through numerical integration.
Better suggested methods:
Lanczos approximation
Stirling's approximation
|
#zkl
|
zkl
|
fcn taylorGamma(x){
var table = T(
0x1p+0, 0x1.2788cfc6fb618f4cp-1,
-0x1.4fcf4026afa2dcecp-1, -0x1.5815e8fa27047c8cp-5,
0x1.5512320b43fbe5dep-3, -0x1.59af103c340927bep-5,
-0x1.3b4af28483e214e4p-7, 0x1.d919c527f60b195ap-8,
-0x1.317112ce3a2a7bd2p-10, -0x1.c364fe6f1563ce9cp-13,
0x1.0c8a78cd9f9d1a78p-13, -0x1.51ce8af47eabdfdcp-16,
-0x1.4fad41fc34fbb2p-20, 0x1.302509dbc0de2c82p-20,
-0x1.b9986666c225d1d4p-23, 0x1.a44b7ba22d628acap-28,
0x1.57bc3fc384333fb2p-28, -0x1.44b4cedca388f7c6p-30,
0x1.cae7675c18606c6p-34, 0x1.11d065bfaf06745ap-37,
-0x1.0423bac8ca3faaa4p-38, 0x1.1f20151323cd0392p-41,
-0x1.72cb88ea5ae6e778p-46, -0x1.815f72a05f16f348p-48,
0x1.6198491a83bccbep-50, -0x1.10613dde57a88bd6p-53,
0x1.5e3fee81de0e9c84p-60, 0x1.a0dc770fb8a499b6p-60,
-0x1.0f635344a29e9f8ep-62, 0x1.43d79a4b90ce8044p-66).reverse();
y := x.toFloat() - 1.0;
sm := table[1,*].reduce('wrap(sm,an){ sm * y + an },table[0]);
return(1.0 / sm);
}
|
http://rosettacode.org/wiki/Hello_world/Text
|
Hello world/Text
|
Hello world/Text is part of Short Circuit's Console Program Basics selection.
Task
Display the string Hello world! on a text console.
Related tasks
Hello world/Graphical
Hello world/Line Printer
Hello world/Newbie
Hello world/Newline omission
Hello world/Standard error
Hello world/Web server
|
#RATFOR
|
RATFOR
|
program hello
write(*,101)"Hello World"
101 format(A)
end
|
http://rosettacode.org/wiki/Function_composition
|
Function composition
|
Task
Create a function, compose, whose two arguments f and g, are both functions with one argument.
The result of compose is to be a function of one argument, (lets call the argument x), which works like applying function f to the result of applying function g to x.
Example
compose(f, g) (x) = f(g(x))
Reference: Function composition
Hint: In some languages, implementing compose correctly requires creating a closure.
|
#Standard_ML
|
Standard ML
|
fun compose (f, g) x = f (g x)
|
http://rosettacode.org/wiki/Function_composition
|
Function composition
|
Task
Create a function, compose, whose two arguments f and g, are both functions with one argument.
The result of compose is to be a function of one argument, (lets call the argument x), which works like applying function f to the result of applying function g to x.
Example
compose(f, g) (x) = f(g(x))
Reference: Function composition
Hint: In some languages, implementing compose correctly requires creating a closure.
|
#SuperCollider
|
SuperCollider
|
f = { |x| x + 1 };
g = { |x| x * 2 };
h = g <> f;
h.(8); // returns 18
|
http://rosettacode.org/wiki/Function_definition
|
Function definition
|
A function is a body of code that returns a value.
The value returned may depend on arguments provided to the function.
Task
Write a definition of a function called "multiply" that takes two arguments and returns their product.
(Argument types should be chosen so as not to distract from showing how functions are created and values returned).
Related task
Function prototype
|
#DWScript
|
DWScript
|
function Multiply(a, b : Integer) : Integer;
begin
Result := a * b;
end;
|
http://rosettacode.org/wiki/Hello_world/Text
|
Hello world/Text
|
Hello world/Text is part of Short Circuit's Console Program Basics selection.
Task
Display the string Hello world! on a text console.
Related tasks
Hello world/Graphical
Hello world/Line Printer
Hello world/Newbie
Hello world/Newline omission
Hello world/Standard error
Hello world/Web server
|
#RASEL
|
RASEL
|
A"!dlroW ,olleH">:?@,Hj
|
http://rosettacode.org/wiki/Function_composition
|
Function composition
|
Task
Create a function, compose, whose two arguments f and g, are both functions with one argument.
The result of compose is to be a function of one argument, (lets call the argument x), which works like applying function f to the result of applying function g to x.
Example
compose(f, g) (x) = f(g(x))
Reference: Function composition
Hint: In some languages, implementing compose correctly requires creating a closure.
|
#Swift
|
Swift
|
func compose<A,B,C>(f: (B) -> C, g: (A) -> B) -> (A) -> C {
return { f(g($0)) }
}
let sin_asin = compose(sin, asin)
println(sin_asin(0.5))
|
http://rosettacode.org/wiki/Function_composition
|
Function composition
|
Task
Create a function, compose, whose two arguments f and g, are both functions with one argument.
The result of compose is to be a function of one argument, (lets call the argument x), which works like applying function f to the result of applying function g to x.
Example
compose(f, g) (x) = f(g(x))
Reference: Function composition
Hint: In some languages, implementing compose correctly requires creating a closure.
|
#Tcl
|
Tcl
|
package require Tcl 8.5
namespace path {::tcl::mathfunc}
proc compose {f g} {
list apply [list {f g x} {{*}$f [{*}$g $x]}] $f $g]
}
set sin_asin [compose sin asin]
{*}$sin_asin 0.5 ;# ==> 0.5
{*}[compose abs int] -3.14 ;# ==> 3
|
http://rosettacode.org/wiki/Function_definition
|
Function definition
|
A function is a body of code that returns a value.
The value returned may depend on arguments provided to the function.
Task
Write a definition of a function called "multiply" that takes two arguments and returns their product.
(Argument types should be chosen so as not to distract from showing how functions are created and values returned).
Related task
Function prototype
|
#Dyalect
|
Dyalect
|
func multiply(a, b) {
a * b
}
|
http://rosettacode.org/wiki/Hello_world/Text
|
Hello world/Text
|
Hello world/Text is part of Short Circuit's Console Program Basics selection.
Task
Display the string Hello world! on a text console.
Related tasks
Hello world/Graphical
Hello world/Line Printer
Hello world/Newbie
Hello world/Newline omission
Hello world/Standard error
Hello world/Web server
|
#REALbasic
|
REALbasic
|
Function Run(args() as String) As Integer
Print "Hello world!"
Quit
End Function
|
http://rosettacode.org/wiki/Function_composition
|
Function composition
|
Task
Create a function, compose, whose two arguments f and g, are both functions with one argument.
The result of compose is to be a function of one argument, (lets call the argument x), which works like applying function f to the result of applying function g to x.
Example
compose(f, g) (x) = f(g(x))
Reference: Function composition
Hint: In some languages, implementing compose correctly requires creating a closure.
|
#TypeScript
|
TypeScript
|
function compose<T, U, V> (fn1: (input: T) => U, fn2: (input: U) => V){
return function(value: T) {
return fn2(fn1(value))
}
}
function size (s: string): number { return s.length; }
function isEven(x: number): boolean { return x % 2 === 0; }
const evenSize = compose(size, isEven);
console.log(evenSize("ABCD")) // true
console.log(evenSize("ABC")) // false
|
http://rosettacode.org/wiki/Function_composition
|
Function composition
|
Task
Create a function, compose, whose two arguments f and g, are both functions with one argument.
The result of compose is to be a function of one argument, (lets call the argument x), which works like applying function f to the result of applying function g to x.
Example
compose(f, g) (x) = f(g(x))
Reference: Function composition
Hint: In some languages, implementing compose correctly requires creating a closure.
|
#uBasic.2F4tH
|
uBasic/4tH
|
Print FUNC(_Compose (_f, _g, 3))
End
_Compose Param (3) : Return (FUNC(a@(FUNC(b@(c@)))))
_f Param (1) : Return (a@ + 1)
_g Param (1) : Return (a@ * 2)
|
http://rosettacode.org/wiki/Function_definition
|
Function definition
|
A function is a body of code that returns a value.
The value returned may depend on arguments provided to the function.
Task
Write a definition of a function called "multiply" that takes two arguments and returns their product.
(Argument types should be chosen so as not to distract from showing how functions are created and values returned).
Related task
Function prototype
|
#D.C3.A9j.C3.A0_Vu
|
Déjà Vu
|
multiply a b:
* a b
|
http://rosettacode.org/wiki/Fortunate_numbers
|
Fortunate numbers
|
Definition
A Fortunate number is the smallest integer m > 1 such that for a given positive integer n, primorial(n) + m is a prime number, where primorial(n) is the product of the first n prime numbers.
For example the first fortunate number is 3 because primorial(1) is 2 and 2 + 3 = 5 which is prime whereas 2 + 2 = 4 is composite.
Task
After sorting and removal of any duplicates, compute and show on this page the first 8 Fortunate numbers or, if your language supports big integers, the first 50 Fortunate numbers.
Related task
Primorial numbers
See also
oeis:A005235 Fortunate numbers
oeis:A046066 Fortunate numbers, sorted with duplicates removed
|
#11l
|
11l
|
F isProbablePrime(n, k = 10)
I n < 2 | n % 2 == 0
R n == 2
V d = n - 1
V s = 0
L d % 2 == 0
d I/= 2
s++
assert(2 ^ s * d == n - 1)
Int nn
I n < 7FFF'FFFF
nn = Int(n)
E
nn = 7FFF'FFFF
L(_) 0 .< k
V a = random:(2 .< nn)
V x = pow(a, d, n)
I x == 1 | x == n - 1
L.continue
L(_) 0 .< s - 1
x = pow(x, 2, n)
I x == 1
R 0B
I x == n - 1
L.break
L.was_no_break
R 0B
R 1B
F is_prime(a)
I a == 2
R 1B
I a < 2 | a % 2 == 0
R 0B
L(i) (3 .. Int(sqrt(a))).step(2)
I a % i == 0
R 0B
R 1B
V primorial = BigInt(1)
V nn = 50
V lim = 75
V s = Set[Int]()
L(n) 1..
I is_prime(n)
primorial *= n
V m = 3
L
I isProbablePrime(primorial + m, 25)
s.add(m)
L.break
m += 2
I --lim == 0
L.break
print(‘First ’nn‘ fortunate numbers:’)
L(m) sorted(Array(s))[0 .< nn]
V i = L.index
print(‘#3’.format(m), end' I (i + 1) % 10 == 0 {"\n"} E ‘ ’)
|
http://rosettacode.org/wiki/Hello_world/Text
|
Hello world/Text
|
Hello world/Text is part of Short Circuit's Console Program Basics selection.
Task
Display the string Hello world! on a text console.
Related tasks
Hello world/Graphical
Hello world/Line Printer
Hello world/Newbie
Hello world/Newline omission
Hello world/Standard error
Hello world/Web server
|
#REBOL
|
REBOL
|
print "Hello world!"
|
http://rosettacode.org/wiki/Function_composition
|
Function composition
|
Task
Create a function, compose, whose two arguments f and g, are both functions with one argument.
The result of compose is to be a function of one argument, (lets call the argument x), which works like applying function f to the result of applying function g to x.
Example
compose(f, g) (x) = f(g(x))
Reference: Function composition
Hint: In some languages, implementing compose correctly requires creating a closure.
|
#UNIX_Shell
|
UNIX Shell
|
compose() {
eval "$1() { $3 | $2; }"
}
downvowel() { tr AEIOU aeiou; }
upcase() { tr a-z A-Z; }
compose c downvowel upcase
echo 'Cozy lummox gives smart squid who asks for job pen.' | c
# => CoZY LuMMoX GiVeS SMaRT SQuiD WHo aSKS FoR JoB PeN.
|
http://rosettacode.org/wiki/Function_composition
|
Function composition
|
Task
Create a function, compose, whose two arguments f and g, are both functions with one argument.
The result of compose is to be a function of one argument, (lets call the argument x), which works like applying function f to the result of applying function g to x.
Example
compose(f, g) (x) = f(g(x))
Reference: Function composition
Hint: In some languages, implementing compose correctly requires creating a closure.
|
#Unlambda
|
Unlambda
|
``s`ksk
|
http://rosettacode.org/wiki/Function_definition
|
Function definition
|
A function is a body of code that returns a value.
The value returned may depend on arguments provided to the function.
Task
Write a definition of a function called "multiply" that takes two arguments and returns their product.
(Argument types should be chosen so as not to distract from showing how functions are created and values returned).
Related task
Function prototype
|
#E
|
E
|
def multiply(a, b) {
return a * b
}
|
http://rosettacode.org/wiki/Fortunate_numbers
|
Fortunate numbers
|
Definition
A Fortunate number is the smallest integer m > 1 such that for a given positive integer n, primorial(n) + m is a prime number, where primorial(n) is the product of the first n prime numbers.
For example the first fortunate number is 3 because primorial(1) is 2 and 2 + 3 = 5 which is prime whereas 2 + 2 = 4 is composite.
Task
After sorting and removal of any duplicates, compute and show on this page the first 8 Fortunate numbers or, if your language supports big integers, the first 50 Fortunate numbers.
Related task
Primorial numbers
See also
oeis:A005235 Fortunate numbers
oeis:A046066 Fortunate numbers, sorted with duplicates removed
|
#Arturo
|
Arturo
|
firstPrimes: select 1..100 => prime?
primorial: function [n][
product first.n: n firstPrimes
]
fortunates: []
i: 1
while [8 > size fortunates][
m: 3
pmi: primorial i
while -> not? prime? m + pmi
-> m: m+2
fortunates: unique fortunates ++ m
i: i + 1
]
print sort fortunates
|
http://rosettacode.org/wiki/Fortunate_numbers
|
Fortunate numbers
|
Definition
A Fortunate number is the smallest integer m > 1 such that for a given positive integer n, primorial(n) + m is a prime number, where primorial(n) is the product of the first n prime numbers.
For example the first fortunate number is 3 because primorial(1) is 2 and 2 + 3 = 5 which is prime whereas 2 + 2 = 4 is composite.
Task
After sorting and removal of any duplicates, compute and show on this page the first 8 Fortunate numbers or, if your language supports big integers, the first 50 Fortunate numbers.
Related task
Primorial numbers
See also
oeis:A005235 Fortunate numbers
oeis:A046066 Fortunate numbers, sorted with duplicates removed
|
#Factor
|
Factor
|
USING: grouping io kernel math math.factorials math.primes
math.ranges prettyprint sequences sets sorting ;
"First 50 distinct fortunate numbers:" print
75 [1,b] [
primorial dup next-prime 2dup - abs 1 =
[ next-prime ] when - abs
] map members natural-sort 50 head 10 group simple-table.
|
http://rosettacode.org/wiki/Fortunate_numbers
|
Fortunate numbers
|
Definition
A Fortunate number is the smallest integer m > 1 such that for a given positive integer n, primorial(n) + m is a prime number, where primorial(n) is the product of the first n prime numbers.
For example the first fortunate number is 3 because primorial(1) is 2 and 2 + 3 = 5 which is prime whereas 2 + 2 = 4 is composite.
Task
After sorting and removal of any duplicates, compute and show on this page the first 8 Fortunate numbers or, if your language supports big integers, the first 50 Fortunate numbers.
Related task
Primorial numbers
See also
oeis:A005235 Fortunate numbers
oeis:A046066 Fortunate numbers, sorted with duplicates removed
|
#FreeBASIC
|
FreeBASIC
|
#include "isprime.bas"
#include "sets.bas"
#include "bubblesort.bas"
function prime(n as uinteger) as uinteger
if n = 1 then return 2
dim as integer c=1, p=3
while c<n
if isprime(p) then c+=1
p += 2
wend
return p
end function
function primorial( n as uinteger ) as ulongint
dim as ulongint ret = 1
for i as uinteger = 1 to n
ret *= prime(i)
next i
return ret
end function
function fortunate(n as uinteger) as uinteger
dim as uinteger m = 3
dim as ulongint pp = primorial(n)
while not isprime(m+pp)
m+=2
wend
return m
end function
redim as integer forts(-1)
dim as integer n = 0, m
while ubound(forts) < 6
n += 1
m = fortunate(n)
if not is_in(m, forts()) then
add_to_set(m, forts())
end if
wend
bubblesort(forts())
for n=0 to 6
print forts(n)
next n
|
http://rosettacode.org/wiki/Hello_world/Text
|
Hello world/Text
|
Hello world/Text is part of Short Circuit's Console Program Basics selection.
Task
Display the string Hello world! on a text console.
Related tasks
Hello world/Graphical
Hello world/Line Printer
Hello world/Newbie
Hello world/Newline omission
Hello world/Standard error
Hello world/Web server
|
#RED
|
RED
|
print "Hello world!"
|
http://rosettacode.org/wiki/Function_composition
|
Function composition
|
Task
Create a function, compose, whose two arguments f and g, are both functions with one argument.
The result of compose is to be a function of one argument, (lets call the argument x), which works like applying function f to the result of applying function g to x.
Example
compose(f, g) (x) = f(g(x))
Reference: Function composition
Hint: In some languages, implementing compose correctly requires creating a closure.
|
#Ursala
|
Ursala
|
compose("f","g") "x" = "f" "g" "x"
|
http://rosettacode.org/wiki/Function_composition
|
Function composition
|
Task
Create a function, compose, whose two arguments f and g, are both functions with one argument.
The result of compose is to be a function of one argument, (lets call the argument x), which works like applying function f to the result of applying function g to x.
Example
compose(f, g) (x) = f(g(x))
Reference: Function composition
Hint: In some languages, implementing compose correctly requires creating a closure.
|
#VBScript
|
VBScript
|
option explicit
class closure
private composition
sub compose( f1, f2 )
composition = f2 & "(" & f1 & "(p1))"
end sub
public default function apply( p1 )
apply = eval( composition )
end function
public property get formula
formula = composition
end property
end class
|
http://rosettacode.org/wiki/Function_definition
|
Function definition
|
A function is a body of code that returns a value.
The value returned may depend on arguments provided to the function.
Task
Write a definition of a function called "multiply" that takes two arguments and returns their product.
(Argument types should be chosen so as not to distract from showing how functions are created and values returned).
Related task
Function prototype
|
#EasyLang
|
EasyLang
|
func multiply a b . r .
r = a * b
.
call multiply 7 5 res
print res
|
http://rosettacode.org/wiki/Fortunate_numbers
|
Fortunate numbers
|
Definition
A Fortunate number is the smallest integer m > 1 such that for a given positive integer n, primorial(n) + m is a prime number, where primorial(n) is the product of the first n prime numbers.
For example the first fortunate number is 3 because primorial(1) is 2 and 2 + 3 = 5 which is prime whereas 2 + 2 = 4 is composite.
Task
After sorting and removal of any duplicates, compute and show on this page the first 8 Fortunate numbers or, if your language supports big integers, the first 50 Fortunate numbers.
Related task
Primorial numbers
See also
oeis:A005235 Fortunate numbers
oeis:A046066 Fortunate numbers, sorted with duplicates removed
|
#Go
|
Go
|
package main
import (
"fmt"
"math/big"
"rcu"
"sort"
)
func main() {
primes := rcu.Primes(379)
primorial := big.NewInt(1)
var fortunates []int
bPrime := new(big.Int)
for _, prime := range primes {
bPrime.SetUint64(uint64(prime))
primorial.Mul(primorial, bPrime)
for j := 3; ; j += 2 {
jj := big.NewInt(int64(j))
bPrime.Add(primorial, jj)
if bPrime.ProbablyPrime(5) {
fortunates = append(fortunates, j)
break
}
}
}
m := make(map[int]bool)
for _, f := range fortunates {
m[f] = true
}
fortunates = fortunates[:0]
for k := range m {
fortunates = append(fortunates, k)
}
sort.Ints(fortunates)
fmt.Println("After sorting, the first 50 distinct fortunate numbers are:")
for i, f := range fortunates[0:50] {
fmt.Printf("%3d ", f)
if (i+1)%10 == 0 {
fmt.Println()
}
}
fmt.Println()
}
|
http://rosettacode.org/wiki/Fortunate_numbers
|
Fortunate numbers
|
Definition
A Fortunate number is the smallest integer m > 1 such that for a given positive integer n, primorial(n) + m is a prime number, where primorial(n) is the product of the first n prime numbers.
For example the first fortunate number is 3 because primorial(1) is 2 and 2 + 3 = 5 which is prime whereas 2 + 2 = 4 is composite.
Task
After sorting and removal of any duplicates, compute and show on this page the first 8 Fortunate numbers or, if your language supports big integers, the first 50 Fortunate numbers.
Related task
Primorial numbers
See also
oeis:A005235 Fortunate numbers
oeis:A046066 Fortunate numbers, sorted with duplicates removed
|
#Haskell
|
Haskell
|
import Data.Numbers.Primes (primes)
import Math.NumberTheory.Primes.Testing (isPrime)
import Data.List (nub)
primorials :: [Integer]
primorials = 1 : scanl1 (*) primes
nextPrime :: Integer -> Integer
nextPrime n
| even n = head $ dropWhile (not . isPrime) [n+1, n+3..]
| even n = nextPrime (n+1)
fortunateNumbers :: [Integer]
fortunateNumbers = (\p -> nextPrime (p + 2) - p) <$> tail primorials
|
http://rosettacode.org/wiki/Hello_world/Text
|
Hello world/Text
|
Hello world/Text is part of Short Circuit's Console Program Basics selection.
Task
Display the string Hello world! on a text console.
Related tasks
Hello world/Graphical
Hello world/Line Printer
Hello world/Newbie
Hello world/Newline omission
Hello world/Standard error
Hello world/Web server
|
#Relation
|
Relation
|
' Hello world!
|
http://rosettacode.org/wiki/Function_composition
|
Function composition
|
Task
Create a function, compose, whose two arguments f and g, are both functions with one argument.
The result of compose is to be a function of one argument, (lets call the argument x), which works like applying function f to the result of applying function g to x.
Example
compose(f, g) (x) = f(g(x))
Reference: Function composition
Hint: In some languages, implementing compose correctly requires creating a closure.
|
#WDTE
|
WDTE
|
let compose f g => (@ c x => g x -> f);
|
http://rosettacode.org/wiki/Function_composition
|
Function composition
|
Task
Create a function, compose, whose two arguments f and g, are both functions with one argument.
The result of compose is to be a function of one argument, (lets call the argument x), which works like applying function f to the result of applying function g to x.
Example
compose(f, g) (x) = f(g(x))
Reference: Function composition
Hint: In some languages, implementing compose correctly requires creating a closure.
|
#Wortel
|
Wortel
|
! @[f g] x ; f(g(x))
|
http://rosettacode.org/wiki/Function_definition
|
Function definition
|
A function is a body of code that returns a value.
The value returned may depend on arguments provided to the function.
Task
Write a definition of a function called "multiply" that takes two arguments and returns their product.
(Argument types should be chosen so as not to distract from showing how functions are created and values returned).
Related task
Function prototype
|
#EchoLisp
|
EchoLisp
|
(define (multiply a b) (* a b)) → multiply ;; (1)
(multiply 1/3 666) → 222
;; a function is a lambda definition :
multiply
→ (λ (_a _b) (#* _a _b))
;; The following is the same as (1) :
(define multiply (lambda(a b) (* a b)))
multiply
→ (🔒 λ (_a _b) (#* _a _b)) ;; a closure
;; a function may be compiled
(lib 'compile)
(compile 'multiply "-float-verbose")
→
💡 [0] compiling _🔶_multiply ((#* _a _b))
;; object code (javascript) :
var ref,top = _blocks[_topblock];
/* */return (
/* */(_stack[top] *_stack[1 + top])
/* */);
multiply → (λ (_a _b) (#🔶_multiply)) ;; compiled function
|
http://rosettacode.org/wiki/Fortunate_numbers
|
Fortunate numbers
|
Definition
A Fortunate number is the smallest integer m > 1 such that for a given positive integer n, primorial(n) + m is a prime number, where primorial(n) is the product of the first n prime numbers.
For example the first fortunate number is 3 because primorial(1) is 2 and 2 + 3 = 5 which is prime whereas 2 + 2 = 4 is composite.
Task
After sorting and removal of any duplicates, compute and show on this page the first 8 Fortunate numbers or, if your language supports big integers, the first 50 Fortunate numbers.
Related task
Primorial numbers
See also
oeis:A005235 Fortunate numbers
oeis:A046066 Fortunate numbers, sorted with duplicates removed
|
#jq
|
jq
|
def primes:
2, range(3; infinite; 2) | select(is_prime);
# generate an infinite stream of primorials
def primorials:
foreach primes as $p (1; .*$p; .);
# Emit a sorted array of the first $limit distinct fortunate numbers
# generated in order of the primoridials
def fortunates($limit):
label $out
| foreach primorials as $p ([];
first( range(3; infinite; 2) | select($p + . | is_prime)) as $q
| . + [$q] | unique;
if length >= $limit then ., break $out else empty end);
fortunates(10)
|
http://rosettacode.org/wiki/Fortunate_numbers
|
Fortunate numbers
|
Definition
A Fortunate number is the smallest integer m > 1 such that for a given positive integer n, primorial(n) + m is a prime number, where primorial(n) is the product of the first n prime numbers.
For example the first fortunate number is 3 because primorial(1) is 2 and 2 + 3 = 5 which is prime whereas 2 + 2 = 4 is composite.
Task
After sorting and removal of any duplicates, compute and show on this page the first 8 Fortunate numbers or, if your language supports big integers, the first 50 Fortunate numbers.
Related task
Primorial numbers
See also
oeis:A005235 Fortunate numbers
oeis:A046066 Fortunate numbers, sorted with duplicates removed
|
#Julia
|
Julia
|
using Primes
primorials(N) = accumulate(*, primes(N), init = big"1")
primorial = primorials(800)
fortunate(n) = nextprime(primorial[n] + 2) - primorial[n]
println("After sorting, the first 50 distinct fortunate numbers are:")
foreach(p -> print(rpad(last(p), 5), first(p) % 10 == 0 ? "\n" : ""),
(map(fortunate, 1:100) |> unique |> sort!)[begin:50] |> enumerate)
|
http://rosettacode.org/wiki/Fortunate_numbers
|
Fortunate numbers
|
Definition
A Fortunate number is the smallest integer m > 1 such that for a given positive integer n, primorial(n) + m is a prime number, where primorial(n) is the product of the first n prime numbers.
For example the first fortunate number is 3 because primorial(1) is 2 and 2 + 3 = 5 which is prime whereas 2 + 2 = 4 is composite.
Task
After sorting and removal of any duplicates, compute and show on this page the first 8 Fortunate numbers or, if your language supports big integers, the first 50 Fortunate numbers.
Related task
Primorial numbers
See also
oeis:A005235 Fortunate numbers
oeis:A046066 Fortunate numbers, sorted with duplicates removed
|
#Mathematica.2FWolfram_Language
|
Mathematica/Wolfram Language
|
ClearAll[primorials]
primorials[n_] := Times @@ Prime[Range[n]]
vals = Table[
primor = primorials[i];
s = NextPrime[primor];
t = NextPrime[s];
Min[DeleteCases[{s - primor, t - primor}, 1]]
,
{i, 100}
];
TakeSmallest[DeleteDuplicates[vals], 50]
|
http://rosettacode.org/wiki/Fortunate_numbers
|
Fortunate numbers
|
Definition
A Fortunate number is the smallest integer m > 1 such that for a given positive integer n, primorial(n) + m is a prime number, where primorial(n) is the product of the first n prime numbers.
For example the first fortunate number is 3 because primorial(1) is 2 and 2 + 3 = 5 which is prime whereas 2 + 2 = 4 is composite.
Task
After sorting and removal of any duplicates, compute and show on this page the first 8 Fortunate numbers or, if your language supports big integers, the first 50 Fortunate numbers.
Related task
Primorial numbers
See also
oeis:A005235 Fortunate numbers
oeis:A046066 Fortunate numbers, sorted with duplicates removed
|
#Nim
|
Nim
|
import algorithm, sequtils, strutils
import bignum
const
N = 50 # Number of fortunate numbers.
Lim = 75 # Number of primorials to compute.
iterator primorials(lim: Positive): Int =
var prime = newInt(2)
var primorial = newInt(1)
for _ in 1..lim:
primorial *= prime
prime = prime.nextPrime()
yield primorial
var list: seq[int]
for p in primorials(Lim):
var m = 3
while true:
if probablyPrime(p + m, 25) != 0:
list.add m
break
inc m, 2
list.sort()
list = list.deduplicate(true)
if list.len < N:
quit "Not enough values. Wanted $1, got $2.".format(N, list.len), QuitFailure
list.setLen(N)
echo "First $# fortunate numbers:".format(N)
for i, m in list:
stdout.write ($m).align(3), if (i + 1) mod 10 == 0: '\n' else: ' '
|
http://rosettacode.org/wiki/Fortunate_numbers
|
Fortunate numbers
|
Definition
A Fortunate number is the smallest integer m > 1 such that for a given positive integer n, primorial(n) + m is a prime number, where primorial(n) is the product of the first n prime numbers.
For example the first fortunate number is 3 because primorial(1) is 2 and 2 + 3 = 5 which is prime whereas 2 + 2 = 4 is composite.
Task
After sorting and removal of any duplicates, compute and show on this page the first 8 Fortunate numbers or, if your language supports big integers, the first 50 Fortunate numbers.
Related task
Primorial numbers
See also
oeis:A005235 Fortunate numbers
oeis:A046066 Fortunate numbers, sorted with duplicates removed
|
#Perl
|
Perl
|
use strict;
use warnings;
use List::Util <first uniq>;
use ntheory qw<pn_primorial is_prime>;
my $upto = 50;
my @candidates;
for my $p ( map { pn_primorial($_) } 1..2*$upto ) {
push @candidates, first { is_prime($_ + $p) } 2..100*$upto;
}
my @fortunate = sort { $a <=> $b } uniq grep { is_prime $_ } @candidates;
print "First $upto distinct fortunate numbers:\n" .
(sprintf "@{['%6d' x $upto]}", @fortunate) =~ s/(.{60})/$1\n/gr;
|
http://rosettacode.org/wiki/Hello_world/Text
|
Hello world/Text
|
Hello world/Text is part of Short Circuit's Console Program Basics selection.
Task
Display the string Hello world! on a text console.
Related tasks
Hello world/Graphical
Hello world/Line Printer
Hello world/Newbie
Hello world/Newline omission
Hello world/Standard error
Hello world/Web server
|
#ReScript
|
ReScript
|
Js.log("Hello world!")
|
http://rosettacode.org/wiki/Function_composition
|
Function composition
|
Task
Create a function, compose, whose two arguments f and g, are both functions with one argument.
The result of compose is to be a function of one argument, (lets call the argument x), which works like applying function f to the result of applying function g to x.
Example
compose(f, g) (x) = f(g(x))
Reference: Function composition
Hint: In some languages, implementing compose correctly requires creating a closure.
|
#Wren
|
Wren
|
var compose = Fn.new { |f, g| Fn.new { |x| f.call(g.call(x)) } }
var double = Fn.new { |x| 2 * x }
var addOne = Fn.new { |x| x + 1 }
System.print(compose.call(double, addOne).call(3))
|
http://rosettacode.org/wiki/Function_composition
|
Function composition
|
Task
Create a function, compose, whose two arguments f and g, are both functions with one argument.
The result of compose is to be a function of one argument, (lets call the argument x), which works like applying function f to the result of applying function g to x.
Example
compose(f, g) (x) = f(g(x))
Reference: Function composition
Hint: In some languages, implementing compose correctly requires creating a closure.
|
#zkl
|
zkl
|
Utils.Helpers.fcomp('+(1),'*(2))(5) //-->11
|
http://rosettacode.org/wiki/Function_definition
|
Function definition
|
A function is a body of code that returns a value.
The value returned may depend on arguments provided to the function.
Task
Write a definition of a function called "multiply" that takes two arguments and returns their product.
(Argument types should be chosen so as not to distract from showing how functions are created and values returned).
Related task
Function prototype
|
#Efene
|
Efene
|
multiply = fn (A, B) {
A * B
}
@public
run = fn () {
io.format("~p~n", [multiply(2, 5)])
}
|
http://rosettacode.org/wiki/Fortunate_numbers
|
Fortunate numbers
|
Definition
A Fortunate number is the smallest integer m > 1 such that for a given positive integer n, primorial(n) + m is a prime number, where primorial(n) is the product of the first n prime numbers.
For example the first fortunate number is 3 because primorial(1) is 2 and 2 + 3 = 5 which is prime whereas 2 + 2 = 4 is composite.
Task
After sorting and removal of any duplicates, compute and show on this page the first 8 Fortunate numbers or, if your language supports big integers, the first 50 Fortunate numbers.
Related task
Primorial numbers
See also
oeis:A005235 Fortunate numbers
oeis:A046066 Fortunate numbers, sorted with duplicates removed
|
#Phix
|
Phix
|
with javascript_semantics
include mpfr.e
mpz primorial = mpz_init(1),
pj = mpz_init()
sequence fortunates = {}
for p=1 to 75 do
mpz_mul_si(primorial,primorial,get_prime(p))
integer j = 3
mpz_add_si(pj,primorial,3)
while not mpz_prime(pj) do
mpz_add_si(pj,pj,2)
j = j + 2
end while
fortunates &= j
end for
fortunates = unique(deep_copy(fortunates))[1..50]
fortunates = join_by(apply(true,sprintf,{{"%3d"},fortunates}),1,10)
printf(1,"The first 50 distinct fortunate numbers are:\n%s\n",{fortunates})
|
http://rosettacode.org/wiki/Fortunate_numbers
|
Fortunate numbers
|
Definition
A Fortunate number is the smallest integer m > 1 such that for a given positive integer n, primorial(n) + m is a prime number, where primorial(n) is the product of the first n prime numbers.
For example the first fortunate number is 3 because primorial(1) is 2 and 2 + 3 = 5 which is prime whereas 2 + 2 = 4 is composite.
Task
After sorting and removal of any duplicates, compute and show on this page the first 8 Fortunate numbers or, if your language supports big integers, the first 50 Fortunate numbers.
Related task
Primorial numbers
See also
oeis:A005235 Fortunate numbers
oeis:A046066 Fortunate numbers, sorted with duplicates removed
|
#Python
|
Python
|
from sympy.ntheory.generate import primorial
from sympy.ntheory import isprime
def fortunate_number(n):
'''Return the fortunate number for positive integer n.'''
# Since primorial(n) is even for all positive integers n,
# it suffices to search for the fortunate numbers among odd integers.
i = 3
primorial_ = primorial(n)
while True:
if isprime(primorial_ + i):
return i
i += 2
fortunate_numbers = set()
for i in range(1, 76):
fortunate_numbers.add(fortunate_number(i))
# Extract the first 50 numbers.
first50 = sorted(list(fortunate_numbers))[:50]
print('The first 50 fortunate numbers:')
print(('{:<3} ' * 10).format(*(first50[:10])))
print(('{:<3} ' * 10).format(*(first50[10:20])))
print(('{:<3} ' * 10).format(*(first50[20:30])))
print(('{:<3} ' * 10).format(*(first50[30:40])))
print(('{:<3} ' * 10).format(*(first50[40:])))
|
http://rosettacode.org/wiki/Hello_world/Text
|
Hello world/Text
|
Hello world/Text is part of Short Circuit's Console Program Basics selection.
Task
Display the string Hello world! on a text console.
Related tasks
Hello world/Graphical
Hello world/Line Printer
Hello world/Newbie
Hello world/Newline omission
Hello world/Standard error
Hello world/Web server
|
#Retro
|
Retro
|
'Hello_world! s:put
|
http://rosettacode.org/wiki/Function_composition
|
Function composition
|
Task
Create a function, compose, whose two arguments f and g, are both functions with one argument.
The result of compose is to be a function of one argument, (lets call the argument x), which works like applying function f to the result of applying function g to x.
Example
compose(f, g) (x) = f(g(x))
Reference: Function composition
Hint: In some languages, implementing compose correctly requires creating a closure.
|
#ZX_Spectrum_Basic
|
ZX Spectrum Basic
|
10 DEF FN f(x)=SQR x
20 DEF FN g(x)=ABS x
30 DEF FN c(x)=FN f(FN g(x))
40 PRINT FN c(-4)
|
http://rosettacode.org/wiki/Function_definition
|
Function definition
|
A function is a body of code that returns a value.
The value returned may depend on arguments provided to the function.
Task
Write a definition of a function called "multiply" that takes two arguments and returns their product.
(Argument types should be chosen so as not to distract from showing how functions are created and values returned).
Related task
Function prototype
|
#Eiffel
|
Eiffel
|
multiply(a, b: INTEGER): INTEGER
do
Result := a*b
end
|
http://rosettacode.org/wiki/Fortunate_numbers
|
Fortunate numbers
|
Definition
A Fortunate number is the smallest integer m > 1 such that for a given positive integer n, primorial(n) + m is a prime number, where primorial(n) is the product of the first n prime numbers.
For example the first fortunate number is 3 because primorial(1) is 2 and 2 + 3 = 5 which is prime whereas 2 + 2 = 4 is composite.
Task
After sorting and removal of any duplicates, compute and show on this page the first 8 Fortunate numbers or, if your language supports big integers, the first 50 Fortunate numbers.
Related task
Primorial numbers
See also
oeis:A005235 Fortunate numbers
oeis:A046066 Fortunate numbers, sorted with duplicates removed
|
#Raku
|
Raku
|
my @primorials = [\*] grep *.is-prime, ^∞;
say display :title("First 50 distinct fortunate numbers:\n"),
(squish sort @primorials[^75].hyper.map: -> $primorial {
(2..∞).first: (* + $primorial).is-prime
})[^50];
sub display ($list, :$cols = 10, :$fmt = '%6d', :$title = "{+$list} matching:\n") {
cache $list;
$title ~ $list.batch($cols)».fmt($fmt).join: "\n"
}
|
http://rosettacode.org/wiki/Fortunate_numbers
|
Fortunate numbers
|
Definition
A Fortunate number is the smallest integer m > 1 such that for a given positive integer n, primorial(n) + m is a prime number, where primorial(n) is the product of the first n prime numbers.
For example the first fortunate number is 3 because primorial(1) is 2 and 2 + 3 = 5 which is prime whereas 2 + 2 = 4 is composite.
Task
After sorting and removal of any duplicates, compute and show on this page the first 8 Fortunate numbers or, if your language supports big integers, the first 50 Fortunate numbers.
Related task
Primorial numbers
See also
oeis:A005235 Fortunate numbers
oeis:A046066 Fortunate numbers, sorted with duplicates removed
|
#REXX
|
REXX
|
/*REXX program finds/displays fortunate numbers N, where N is specified (default=8).*/
numeric digits 12
parse arg n cols . /*obtain optional argument from the CL.*/
if n=='' | n=="," then n= 8 /*Not specified? Then use the default.*/
if cols=='' | cols=="," then cols= 10 /* " " " " " " */
call genP n**2 /*build array of semaphores for primes.*/
pp.= 1
do i=1 for n+1; im= i - 1; pp.i= pp.im * @.i /*calculate primorial numbers*/
end /*i*/
i=i-1; call genp pp.i + 1000
title= ' fortunate numbers'
w= 10 /*maximum width of a number in any col.*/
say ' index │'center(title, 1 + cols*(w+1) )
say '───────┼'center("" , 1 + cols*(w+1), '─')
found= 0; idx= 1 /*number of fortunate (so far) & index.*/
!!.= 0; maxFN= 0 /*(stemmed) array of fortunate numbers*/
do j=1 until found==n; pt= pp.j /*search for fortunate numbers in range*/
pt= pp.j /*get the precalculated primorial prime*/
do m=3 by 2; t= pt + m /*find M that satisfies requirement. */
if !.t=='' then leave /*Is !.t prime? Then we found a good M*/
end /*m*/
if !!.m then iterate /*Fortunate # already found? Then skip*/
!!.m= 1; found= found + 1 /*assign fortunate number; bump count.*/
maxFN= max(maxFN, t) /*obtain max fortunate # for displaying*/
end /*j*/
$=; finds= 0 /*$: line of output; FINDS: count.*/
do k=1 for maxFN; if \!!.k then iterate /*show the fortunate numbers we found. */
finds= finds + 1 /*bump the count of numbers (for $). */
c= commas(k) /*maybe add commas to the number. */
$= $ right(c, max(w, length(c) ) ) /*add a nice prime ──► list, allow big#*/
if found//cols\==0 then iterate /*have we populated a line of output? */
say center(idx, 7)'│' substr($, 2); $= /*display what we have so far (cols). */
idx= idx + cols /*bump the index count for the output*/
end /*k*/
if $\=='' then say center(idx, 7)"│" substr($, 2) /*possible display residual output.*/
say '───────┴'center("" , 1 + cols*(w+1), '─') /*display the foot separator. */
say
say 'Found ' commas(found) title
exit 0 /*stick a fork in it, we're all done. */
/*──────────────────────────────────────────────────────────────────────────────────────*/
commas: parse arg ?; do jc=length(?)-3 to 1 by -3; ?=insert(',', ?, jc); end; return ?
/*──────────────────────────────────────────────────────────────────────────────────────*/
genP: @.1=2; @.2=3; @.3=5; @.4=7; @.5=11 /*define some low primes. */
!.=0; !.2=; !.3=; !.5=; !.7=; !.11= /* " " " " semaphores. */
#= 5; sq.#= @.#**2 /*squares of low primes.*/
do j=@.#+2 by 2 to arg(1) /*find odd primes from here on. */
parse var j '' -1 _; if _==5 then iterate /*J ÷ by 5 ? */
if j//3==0 then iterate; if j//7==0 then iterate /*" " " 3?; J ÷ by 7 ? */
do k=5 while sq.k<=j /* [↓] divide by the known odd primes.*/
if j // @.k == 0 then iterate j /*Is J ÷ X? Then not prime. ___ */
end /*k*/ /* [↑] only process numbers ≤ √ J */
#= #+1; @.#= j; sq.#= j*j; !.j= /*bump # of Ps; assign next P; P²; P# */
end /*j*/; return
|
http://rosettacode.org/wiki/Hello_world/Text
|
Hello world/Text
|
Hello world/Text is part of Short Circuit's Console Program Basics selection.
Task
Display the string Hello world! on a text console.
Related tasks
Hello world/Graphical
Hello world/Line Printer
Hello world/Newbie
Hello world/Newline omission
Hello world/Standard error
Hello world/Web server
|
#REXX
|
REXX
|
/*REXX program to show a line of text. */
say 'Hello world!'
|
http://rosettacode.org/wiki/Function_definition
|
Function definition
|
A function is a body of code that returns a value.
The value returned may depend on arguments provided to the function.
Task
Write a definition of a function called "multiply" that takes two arguments and returns their product.
(Argument types should be chosen so as not to distract from showing how functions are created and values returned).
Related task
Function prototype
|
#Ela
|
Ela
|
multiply x y = x * y
|
http://rosettacode.org/wiki/Fortunate_numbers
|
Fortunate numbers
|
Definition
A Fortunate number is the smallest integer m > 1 such that for a given positive integer n, primorial(n) + m is a prime number, where primorial(n) is the product of the first n prime numbers.
For example the first fortunate number is 3 because primorial(1) is 2 and 2 + 3 = 5 which is prime whereas 2 + 2 = 4 is composite.
Task
After sorting and removal of any duplicates, compute and show on this page the first 8 Fortunate numbers or, if your language supports big integers, the first 50 Fortunate numbers.
Related task
Primorial numbers
See also
oeis:A005235 Fortunate numbers
oeis:A046066 Fortunate numbers, sorted with duplicates removed
|
#Ruby
|
Ruby
|
require "gmp"
primorials = Enumerator.new do |y|
cur = prod = 1
loop {y << prod *= (cur = GMP::Z(cur).nextprime)}
end
limit = 50
fortunates = []
while fortunates.size < limit*2 do
prim = primorials.next
fortunates << (GMP::Z(prim+2).nextprime - prim)
fortunates = fortunates.uniq.sort
end
p fortunates[0, limit]
|
http://rosettacode.org/wiki/Fortunate_numbers
|
Fortunate numbers
|
Definition
A Fortunate number is the smallest integer m > 1 such that for a given positive integer n, primorial(n) + m is a prime number, where primorial(n) is the product of the first n prime numbers.
For example the first fortunate number is 3 because primorial(1) is 2 and 2 + 3 = 5 which is prime whereas 2 + 2 = 4 is composite.
Task
After sorting and removal of any duplicates, compute and show on this page the first 8 Fortunate numbers or, if your language supports big integers, the first 50 Fortunate numbers.
Related task
Primorial numbers
See also
oeis:A005235 Fortunate numbers
oeis:A046066 Fortunate numbers, sorted with duplicates removed
|
#Sidef
|
Sidef
|
func fortunate(n) {
var P = n.pn_primorial
2..Inf -> first {|m| P+m -> is_prob_prime }
}
var limit = 50
var uniq = Set()
var all = []
for (var n = 1; uniq.len < 2*limit; ++n) {
var m = fortunate(n)
all << m
uniq << m
}
say "Fortunate numbers for n = 1..#{limit}:"
say all.first(limit)
say "\n#{limit} Fortunate numbers, sorted with duplicates removed:"
say uniq.sort.first(limit)
|
http://rosettacode.org/wiki/Fortunate_numbers
|
Fortunate numbers
|
Definition
A Fortunate number is the smallest integer m > 1 such that for a given positive integer n, primorial(n) + m is a prime number, where primorial(n) is the product of the first n prime numbers.
For example the first fortunate number is 3 because primorial(1) is 2 and 2 + 3 = 5 which is prime whereas 2 + 2 = 4 is composite.
Task
After sorting and removal of any duplicates, compute and show on this page the first 8 Fortunate numbers or, if your language supports big integers, the first 50 Fortunate numbers.
Related task
Primorial numbers
See also
oeis:A005235 Fortunate numbers
oeis:A046066 Fortunate numbers, sorted with duplicates removed
|
#Wren
|
Wren
|
import "/math" for Int
import "/big" for BigInt
import "/sort" for Sort
import "/seq" for Lst
import "/fmt" for Fmt
var primes = Int.primeSieve(379)
var primorial = BigInt.one
var fortunates = []
for (prime in primes) {
primorial = primorial * prime
var j = 3
while (true) {
if ((primorial + j).isProbablePrime(5)) {
fortunates.add(j)
break
}
j = j + 2
}
}
fortunates = Lst.distinct(fortunates)
Sort.quick(fortunates)
System.print("After sorting, the first 50 distinct fortunate numbers are:")
for (chunk in Lst.chunks(fortunates[0..49], 10)) Fmt.print("$3d", chunk)
|
http://rosettacode.org/wiki/Hello_world/Text
|
Hello world/Text
|
Hello world/Text is part of Short Circuit's Console Program Basics selection.
Task
Display the string Hello world! on a text console.
Related tasks
Hello world/Graphical
Hello world/Line Printer
Hello world/Newbie
Hello world/Newline omission
Hello world/Standard error
Hello world/Web server
|
#Ring
|
Ring
|
See "Hello world!"
|
http://rosettacode.org/wiki/Function_definition
|
Function definition
|
A function is a body of code that returns a value.
The value returned may depend on arguments provided to the function.
Task
Write a definition of a function called "multiply" that takes two arguments and returns their product.
(Argument types should be chosen so as not to distract from showing how functions are created and values returned).
Related task
Function prototype
|
#Elena
|
Elena
|
real multiply(real a, real b)
= a * b;
|
http://rosettacode.org/wiki/Hello_world/Text
|
Hello world/Text
|
Hello world/Text is part of Short Circuit's Console Program Basics selection.
Task
Display the string Hello world! on a text console.
Related tasks
Hello world/Graphical
Hello world/Line Printer
Hello world/Newbie
Hello world/Newline omission
Hello world/Standard error
Hello world/Web server
|
#Risc-V
|
Risc-V
|
.data
hello:
.string "Hello World!\n\0"
.text
main:
la a0, hello
li a7, 4
ecall
li a7, 10
ecall
|
http://rosettacode.org/wiki/Function_definition
|
Function definition
|
A function is a body of code that returns a value.
The value returned may depend on arguments provided to the function.
Task
Write a definition of a function called "multiply" that takes two arguments and returns their product.
(Argument types should be chosen so as not to distract from showing how functions are created and values returned).
Related task
Function prototype
|
#Elixir
|
Elixir
|
defmodule RosettaCode do
def multiply(x,y) do
x * y
end
def task, do: IO.puts multiply(3,5)
end
RosettaCode.task
|
http://rosettacode.org/wiki/Hello_world/Text
|
Hello world/Text
|
Hello world/Text is part of Short Circuit's Console Program Basics selection.
Task
Display the string Hello world! on a text console.
Related tasks
Hello world/Graphical
Hello world/Line Printer
Hello world/Newbie
Hello world/Newline omission
Hello world/Standard error
Hello world/Web server
|
#RTL.2F2
|
RTL/2
|
TITLE Goodbye World;
LET NL=10;
EXT PROC(REF ARRAY BYTE) TWRT;
ENT PROC INT RRJOB();
TWRT("Hello world!#NL#");
RETURN(1);
ENDPROC;
|
http://rosettacode.org/wiki/Function_definition
|
Function definition
|
A function is a body of code that returns a value.
The value returned may depend on arguments provided to the function.
Task
Write a definition of a function called "multiply" that takes two arguments and returns their product.
(Argument types should be chosen so as not to distract from showing how functions are created and values returned).
Related task
Function prototype
|
#Elm
|
Elm
|
--There are multiple ways to create a function in Elm
--This is a named function
multiply x y = x*y
--This is an anonymous function
\x y -> x*y
|
http://rosettacode.org/wiki/Hello_world/Text
|
Hello world/Text
|
Hello world/Text is part of Short Circuit's Console Program Basics selection.
Task
Display the string Hello world! on a text console.
Related tasks
Hello world/Graphical
Hello world/Line Printer
Hello world/Newbie
Hello world/Newline omission
Hello world/Standard error
Hello world/Web server
|
#Ruby
|
Ruby
|
puts "Hello world!"
|
http://rosettacode.org/wiki/Function_definition
|
Function definition
|
A function is a body of code that returns a value.
The value returned may depend on arguments provided to the function.
Task
Write a definition of a function called "multiply" that takes two arguments and returns their product.
(Argument types should be chosen so as not to distract from showing how functions are created and values returned).
Related task
Function prototype
|
#Emacs_Lisp
|
Emacs Lisp
|
(defun multiply (x y)
(* x y))
|
http://rosettacode.org/wiki/Hello_world/Text
|
Hello world/Text
|
Hello world/Text is part of Short Circuit's Console Program Basics selection.
Task
Display the string Hello world! on a text console.
Related tasks
Hello world/Graphical
Hello world/Line Printer
Hello world/Newbie
Hello world/Newline omission
Hello world/Standard error
Hello world/Web server
|
#Run_BASIC
|
Run BASIC
|
print "Hello world!"
|
http://rosettacode.org/wiki/Function_definition
|
Function definition
|
A function is a body of code that returns a value.
The value returned may depend on arguments provided to the function.
Task
Write a definition of a function called "multiply" that takes two arguments and returns their product.
(Argument types should be chosen so as not to distract from showing how functions are created and values returned).
Related task
Function prototype
|
#Erlang
|
Erlang
|
% Implemented by Arjun Sunel
-module(func_definition).
-export([main/0]).
main() ->
K=multiply(3,4),
io :format("~p~n",[K]).
multiply(A,B) ->
case {A,B} of
{A, B} -> A * B
end.
|
http://rosettacode.org/wiki/Hello_world/Text
|
Hello world/Text
|
Hello world/Text is part of Short Circuit's Console Program Basics selection.
Task
Display the string Hello world! on a text console.
Related tasks
Hello world/Graphical
Hello world/Line Printer
Hello world/Newbie
Hello world/Newline omission
Hello world/Standard error
Hello world/Web server
|
#Rust
|
Rust
|
fn main() {
print!("Hello world!");
}
|
http://rosettacode.org/wiki/Function_definition
|
Function definition
|
A function is a body of code that returns a value.
The value returned may depend on arguments provided to the function.
Task
Write a definition of a function called "multiply" that takes two arguments and returns their product.
(Argument types should be chosen so as not to distract from showing how functions are created and values returned).
Related task
Function prototype
|
#ERRE
|
ERRE
|
FUNCTION f(x,y,z,…)
f=formula
END FUNCTION
|
http://rosettacode.org/wiki/Hello_world/Text
|
Hello world/Text
|
Hello world/Text is part of Short Circuit's Console Program Basics selection.
Task
Display the string Hello world! on a text console.
Related tasks
Hello world/Graphical
Hello world/Line Printer
Hello world/Newbie
Hello world/Newline omission
Hello world/Standard error
Hello world/Web server
|
#Salmon
|
Salmon
|
"Hello world!"!
|
http://rosettacode.org/wiki/Function_definition
|
Function definition
|
A function is a body of code that returns a value.
The value returned may depend on arguments provided to the function.
Task
Write a definition of a function called "multiply" that takes two arguments and returns their product.
(Argument types should be chosen so as not to distract from showing how functions are created and values returned).
Related task
Function prototype
|
#Euphoria
|
Euphoria
|
function multiply( atom a, atom b )
return a * b
end function
|
http://rosettacode.org/wiki/Hello_world/Text
|
Hello world/Text
|
Hello world/Text is part of Short Circuit's Console Program Basics selection.
Task
Display the string Hello world! on a text console.
Related tasks
Hello world/Graphical
Hello world/Line Printer
Hello world/Newbie
Hello world/Newline omission
Hello world/Standard error
Hello world/Web server
|
#SAS
|
SAS
|
/* Using a data step. Will print the string in the log window */
data _null_;
put "Hello world!";
run;
|
http://rosettacode.org/wiki/Function_definition
|
Function definition
|
A function is a body of code that returns a value.
The value returned may depend on arguments provided to the function.
Task
Write a definition of a function called "multiply" that takes two arguments and returns their product.
(Argument types should be chosen so as not to distract from showing how functions are created and values returned).
Related task
Function prototype
|
#F.23
|
F#
|
let multiply x y = x * y // integer
let fmultiply (x : float) (y : float) = x * y
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.