The F# char
type is a 16 bit value to represent the smallest addressable components of text, immutable by default.
char
s can be defined as literals with single quotes:
let ch = 'A'
// => val ch: char = 'A'
Strings are a sequence of chars.
An individual char
can be retrieved from a string with (zero-based) indexing:
"Exercism"[4] // => 'c'
Iterating over a string returns a char
at each step.
The next example uses a higher order function and an anonymous function, for convenience. These will be covered properly later in the syllabus, but for now they are essentially a concise way to write a loop over the characters in a string.
Seq.map (fun c -> c, int c) "F#" // => [('F', 70); ('#', 35)]
As shown above, a char
can be cast to its int
value.
This also works (at least some of the time) for other scripts:
Seq.map (fun c -> c, int c) "東京" // => [('東', 26481); ('京', 20140)]
The underlying Int16 is used when comparing characters:
'A' < 'D' // => true
Also, an int
can be cast to char
:
char 77 // => 'M'
The System.Char
library contains the full set of methods expected for a .NET language, such as upper/lower conversions:
'a' |> System.Char.ToUpper // => 'A'
'Q' |> System.Char.ToLower // => 'q'
In this exercise you will implement a partial set of utility routines to help a developer clean up identifier names.
In the 6 tasks you will gradually build up the functions transform
to convert single characters and clean
to convert strings.
A valid identifier comprises zero or more letters, underscores, hyphens, question marks and emojis.
If an empty string is passed to the clean
function, an empty string should be returned.
Implement the transform
function to replace any hyphens with underscores.
transform '-' // => "_"
Remove all whitespace characters. This will include leading and trailing whitespace.
transform ' ' // => ""
Modify the transform
function to convert camelCase to kebab-case
transform 'D' // => "-d"
Modify the transform
function to omit any characters that are numeric.
transform '7' // => ""
Modify the transform
function to replace any Greek letters in the range 'α' to 'ω'.
transform 'β' // => "?"
Implement the clean
function to apply these operations to an entire string.
Characters which fall outside the rules should pass through unchanged.
clean " a2b Cd-ω😀 " // => "ab-cd_?😀"
This topic will be covered in detail later in the syllabus.
For now, it may be useful to know that there is a higher order function called String.collect
that converts a collection of char
s to a string, using a function that you supply.
let transform ch = $"{ch}_"
String.collect transform "abc" // => "a_b_c_"
Sign up to Exercism to learn and master F# with 15 concepts, 142 exercises, and real human mentoring, all for free.