Best way to implement very simple F# function - f#

I'm very new to F#, and functional programming, I started learning today! Is this is the best way to implement a function that returns if a string has a digit?
open System;
let stringHasDigit (str: String) =
not (String.forall(fun c -> (Char.IsDigit(c) = false)) str)
printfn "%b" (stringHasDigit "This string has 1 digits")

Look for functions in String before looking in Seq. They tend to be faster. This is twice as fast as using Seq.exists
let stringHasDigit (s: string) =
String.exists Char.IsDigit s
Btw, you don't need semicolon at the end of the open statement.

SInce string is a sequence of Chars, one can use functions from the Seq module:
let hasDigits (s: string) =
s |> Seq.exists Char.IsDigit

Related

F# - How to access function parameters that have no name?

The function below compiles and runs fine.
I do not intend to create them like this (without parameter names).
However because it lets me create such a function, I am curious how I can access them within the function.
let testfunction string int =
printfn "Inside Method"
testfunction "a" 5
Here is the F# interactive output
Inside Method
val testfunction: string: 'a -> int: 'b -> unit
val it: unit = ()
Thank you for your help in advance.
Actually, string and int are the parameter names, so you access them like any other parameters:
let testfunction string int =
printfn $"string is {string}"
printfn $"int is {int}"
testfunction "a" 5
Output is:
string is a
int is 5
To reduce confusion, you could declare the function like this:
let testfunction (string : string) (int : int) =
printfn $"string is {string}"
printfn $"int is {int}"

F# Chaining functions that return tuple

I am new to F# and am trying to chain functions to make a Higher Order Function.
A simplified example is
init returns a tuple
validate accepts a tuple and returns bool
let init : string * string =
("1", "2")
let validate ((a: string), (b: string)) : bool =
a.Equals(b)
let test = init >> validate
ERROR
This expression was expected to have type 'a -> 'b' but here has type 'string * string'
As the answer for Piotr explains, you are getting an error because you have a value and a function. To compose those, you can turn init into a function, but you do not really need to use composition in this case.
If you want to pass a value as an argument to a function, it is typically much simpler to just pass it as an argument:
let res = validate init
Alternatively, if you have a number of functions you want to apply to your input in a sequence, you can do this using the piping operator:
let res = init |> validate
Function composition using >> is a nice functional trick, but I think it is actually much less common in standard F# code than most people think. I use |> all the time, but >> only rarely.
You can only compose functions using the >> combinator. Your first assignment is not a function - it is a binding to a value - your tuple.
You can convert it to a function just by adding empty parameter list () (unit) parameter like this:
let init() : string * string =
("1", "2")
let validate ((a: string), (b: string)) : bool =
a.Equals(b)
let test = init >> validate
let res = test()

How to pick correct method overload for function composition?

Here is a simple composition of functions in F#
let composedFunction = System.Text.Encoding.UTF8.GetBytes >> Array.length
"test" |> composedFunction
Type inference correctly defines the type of composed function string -> int. But compiler cannot pick correct overload of System.Text.Encoding.UTF8.GetBytes method:
Error FS0041: A unique overload for method 'GetBytes' could not be
determined based on type information prior to this program point. A
type annotation may be needed. Candidates:
System.Text.Encoding.GetBytes(chars: char []) : byte [],
System.Text.Encoding.GetBytes(s: string) : byte []Blockquote
Is there any way to compose correct overload of System.Text.Encoding.UTF8.GetBytes which accepts string parameter?
Or course, I can do following
// declare function which calls correct overload and then use it for compostion
let getBytes (s: string) = System.Text.Encoding.UTF8.GetBytes s
let composedFunction = getBytes >> Array.length
// start composition with ugly lambda
let composedFunction =
(fun (s: string) -> s) >> System.Text.Encoding.UTF8.GetBytes >> Array.length
But I wonder if there is any way without additional function declarations to make the compiler pick right overload according to the inferred string -> int type of composed function?
You can always add annotations:
let composedFunction : string -> _ = System.Text.Encoding.UTF8.GetBytes >> Array.length
or
let composedFunction = (System.Text.Encoding.UTF8.GetBytes : string -> _) >> Array.length
As your example shows, .NET methods do not always compose well - I think the idiomatic approach in such situations is just to use the .NET style when you're dealing with .NET libraries (and use functional style when you're dealing with functional libraries).
In your specific case, I would just define a normal function with type annotation and get the length using the Length member rather than using the function:
let composedFunction (s:string) =
System.Text.Encoding.UTF8.GetBytes(s).Length
The existing answer shows how to get the composition to work with type annotations. Another trick you can do (which I would definitely not use in practice) is that you can add identity function on string to the composition to constrain the types:
let composedFunction = id<string> >> System.Text.Encoding.UTF8.GetBytes >> Array.length
It's fun that this works, but as I said, I would never actually use this, because a normal function as defined above is much easier to understand.

How to pass F# a string and get the result back in c# [duplicate]

This question already has answers here:
Call F# code from C#
(4 answers)
Closed 8 years ago.
I am SQL developer and am really new to both F# and C#. I need help on how to pass a string to f# function below and to return the result from F# to C#.
Description of project:
I am using stanford postagger to tag a sentence with the parts of speech.
Reference link from where i copied this code.
(http://sergey-tihon.github.io/Stanford.NLP.NET/StanfordPOSTagger.html)
module File1
open java.io
open java.util
open edu.stanford.nlp.ling
open edu.stanford.nlp.tagger.maxent
// Path to the folder with models
let modelsDirectry =
__SOURCE_DIRECTORY__ + #'..\stanford-postagger-2013-06-20\models\'
// Loading POS Tagger
let tagger = MaxentTagger(modelsDirectry + 'wsj-0-18-bidirectional-nodistsim.tagger')
let tagTexrFromReader (reader:Reader) =
let sentances = MaxentTagger.tokenizeText(reader).toArray()
sentances |> Seq.iter (fun sentence ->
let taggedSentence = tagger.tagSentence(sentence :?> ArrayList)
printfn "%O" (Sentence.listToString(taggedSentence, false))
)
// Text for tagging
let text = System.Console.ReadLine();
tagTexrFromReader <| new StringReader(text)
it won't matter if C# or F# - do make a function that gets a string and returns ... let
s say an int, you just need something like this (put it in some MyModule.fs):
namespace MyNamespace
module MyModule =
// this is your function with one argument (a string named input) and result of int
let myFun (input : string) : int =
// do whatever you have to
5 // the value of the last line will be your result - in this case a integer 5
call it in from C#/.net with
int result = MyNamespace.MyModule.myFun ("Hallo");
I hope this helps you out a bit
For your example this would be:
let myFun (text : string) =
use reader = new StringReader(text)
tagTexrFromReader reader
as you'll have this in the module File1 you can just call it with var res = Fiel1.myFun(text);
BTW: use is in there because StringReader is IDisposable and using use F# will dispose the object when you exit the scope.
PS: is tagTexrFromReader a typo?

F# GetDigitValue value or construct not valid

I am new to F# and would like to have an advice.
I would like to use the GetDigitValue function.
open System
open System.Drawing
open System.Globalization
let getSubscript ichar =
match ichar with
|1 -> GetDigitValue(843)
| _ -> GetDigitVale(852)
I have the following error: The value or constructor 'getDigitValue" is not defined.
Without further information I can't really tell what you are trying to do.
GetDigitValue is a static method of the CharUnicodeInfo class.
It is used like this:
let testString = "1234567890"
let digitValue = CharUnicodeInfo.GetDigitValue(testString, 3)
This returns the digit value for the 3rd character in the string. It also works with a single character too.
let test = '5'
let digitvalue = CharUnicodeInfo.GetDigitValue(test)
Update:
To get the superscript of a string I think the Numeric value will return this:
let superscriptTwo ="U+00B2"
let numericvalue = CharUnicodeInfo.GetNumericValue(superscriptTwo)
I would like to get the superscript of numbers.
Then I think you want this function that gives a unicode character that is the superscript of the given digit:
let superscriptOf n =
if 0<=n && n<10 then "⁰¹²³⁴⁵⁶⁷⁸⁹".[n] else
invalidArg "n" "Not a single digit number"
Note that F# supports unicode in F# code. You can even use unicode variable names like λ in F# code!

Resources