Type mismatch error - f#

Here is my code:
open System
let rec gcd a b =
match b with
| x when x = 0 -> a
| _ -> gcd(b, a % b)
let result = gcd 15 10
[<EntryPoint>]
let main(args : string[]) =
printfn "result = %d" result
0
Why I get the error with this code:
D:\datahub\Dropbox\development\myprojects\project-euler\Problem_5\problem_5.fs(6,16): error FS0001: Type mismatch. Expec
ting a
'a
but given a
int -> 'a
The resulting type would be infinite when unifying ''a' and 'int -> 'a'

The example tries to separate arguments by using a comma. In F# multiple arguments are supplied to a function by separating them with whitespace:
let rec gcd a b =
match b with
| x when x = 0 -> a
| _ -> gcd b (a % b)

Related

F# Monad how fix datatypes

I am trying to write a Monad in F# but I can not compile the code and I am getting error FS0001
error: This expression was expected to have type 'Result' but here has type '(Result<'a> -> Result<'b>) -> Result<'b>'
open System
type Result<'TSuccess> =
| Success of 'TSuccess
| Failure
let bind x f =
match x with
| Success x -> f (Success x)
| Failure -> Failure
let stringToInt (s:string) =
try
let result = s |> int
Success result
with
|_-> Failure
let isPositive (i:int) =
if ( i > 0) then Success i : Result<int>
else Failure
let toString (i:int) =
try
let result = i |> string
Success result
with
|_ -> Failure
let bindIsPositive = bind isPositive : Result<int>
let bindToString = bind toString : Result<string>
let (>>=) x f = bind f x
let strintToIntIsPositiveIntToString s = stringToInt >>= bindIsPositive >>= bindToString
[<EntryPoint>]
let main argv =
printfn "10"
let mys = strintToIntIsPositiveIntToString "9"
Console.WriteLine mys.ToString
0 // return an integer exit code
First of all, the type of your bind is not right:
your version : Result<'a> -> (Result<'a> -> Result<'b>) -> Result<'b>
typical type : Result<'a> -> ('a -> Result<'b>) -> Result<'b>
It will also be a lot easier to do the rest if you switch the order of parameters to get:
bind : ('a -> Result<'b>) -> Result<'a> -> Result<'b>
So, you can use the following bind:
let bind f x =
match x with
| Success x -> f x
| Failure -> Failure
Once you do this, you can define bindIsPositive and bindToString. The bind operation now takes a function as a first argument, so this works but you have to remove your type annotation:
let bindIsPositive = bind isPositive
let bindToString = bind toString
When composing functions, you can then either use your >>= operator, or use normal F# piping and bind functions:
let strintToIntIsPositiveIntToString x = x |> stringToInt |> bindIsPositive |> bindToString
let strintToIntIsPositiveIntToString x = x >>= stringToInt >>= isPositive >>= toString

using a sequence on partial application

I have a sequence of value that I would like to apply to a function partially :
let f a b c d e= a+b+c+d+e
let items = [1,2,3,4,5]
let result = applyPartially f items
Assert.Equal(15, result)
I am looking after the applyPartially function. I have tried writing recursive functions like this :
let rec applyPartially f items =
| [] -> f
| [x] -> f x
| head :: tail -> applyPartially (f head) tail
The problem I have encountered is that the f type is at the beginning of my iteration 'a->'b->'c->'d->'e, and for every loop it should consume an order.
'a->'b->'c->'d->'e
'b->'c->'d->'e
'c->'d->'e
'd->'e
That means that the lower interface I can think of would be 'd->'e. How could I hide the complexity of my function so that only 'd->'e is shown in the recursive function?
The F# type system does not have a nice way of working with ordinary functions in a way you are suggesting - to do this, you'd need to make sure that the length of the list matches the number of arguments of the function, which is not possible with ordinary lists and functions.
However, you can model this nicely using a discriminated union. You can define a partial function, which has either completed, or needs one more input:
type PartialFunction<'T, 'R> =
| Completed of 'R
| NeedsMore of ('T -> PartialFunction<'T, 'R>)
Your function f can now be written (with a slightly ugly syntax) as a PartialFunction<int, int> that keeps taking 5 inputs and then returns the result:
let f =
NeedsMore(fun a -> NeedsMore(fun b ->
NeedsMore(fun c -> NeedsMore(fun d ->
NeedsMore(fun e -> Completed(a+b+c+d+e))))))
Now you can implement applyPartially by deconstructing the list of arguments and applying them one by one to the partial function until you get the result:
let rec applyPartially f items =
match f, items with
| Completed r, _ -> r
| NeedsMore f, head::tail -> applyPartially (f head) tail
| NeedsMore _, _ -> failwith "Insufficient number of arguments"
The following now returns 15 as expected:
applyPartially f [1;2;3;4;5]
Disclaimer: Please don't use this. This is just plain evil.
let apply f v =
let args = v |> Seq.toArray
f.GetType().GetMethods()
|> Array.tryFind (fun m -> m.Name = "Invoke" && Array.length (m.GetParameters()) = Array.length args)
|> function None -> failwith "Not enough args" | Some(m) -> m.Invoke(f, args)
Just like you would expect:
let f a b c d e= a+b+c+d+e
apply f [1; 2; 3; 4; 5] //15

F# Monad multiple parameters

I am trying to wrap my head around monads and how to use them in real world examples. The first "task" i set myself is to write an "Exception Monad" which of course (at this point) is nothing more than the "Either monad" twisted to suit my purpose.
My code looks like this:
type MException<'a> =
| Success of 'a
| Failure of string
with
static member returnM a =
Success a
static member bind f =
fun e ->
match e with
| Success a -> f a
| Failure m -> Failure m
static member map f =
fun e ->
match e with
| Success a -> Success (f a)
| Failure m -> Failure m
// Create a little test case to test my code
let divide (n, m) =
match m with
| 0 -> Failure "Cannot divide by zero"
| _ -> Success ((float n) / (float m))
let round (f:float) =
Success ( System.Math.Round(f, 3) )
let toString (f:float) =
sprintf "%f" f
let divideRoundAndPrintNumber =
divide
>> MException<_>.bind round
>> MException<_>.map toString
// write the result
let result = divideRoundAndPrintNumber (11, 3)
match result with
| Success r -> printf "%s\n" r
| Failure m -> printf "%s\n" m
My question is the following: the divide function now takes a tuple. What can or should I do to make the bind and map functions behave correctly for functions with multiple parameters?
EDIT 30-12-2015:
Both the answers and comments of #Mark Seemann helped find the answer to the problem. #Mikhail provided the implementation of the solution. Currying is the right way of solving the problem. Computation Expressions are not a solution but a syntax abstraction which does work but gets complicated once you add async and other patterns to the problem. "Simple" composition seems like the easiest and "trueest" solution.
Change divideRoundAndPrintNumber to be a function instead of a value
let divide n m =
match m with
| 0 -> Failure "Cannot divide by zero"
| _ -> Success ((float n) / (float m))
let divideRoundAndPrintNumber n =
divide n
>> MException<_>.bind round
>> MException<_>.map toString
Unfortunately I do not know enough about F# to understand your code completely. For example I do not understand the >> operator and the MException<_> expression. But I can give you an alternative solution for your problem. It utilzies a F# feature called "Computation Expressions". It enables you to do "Monadic" magic in a nice F#-like way:
type MException<'a> =
| Success of 'a
| Failure of string
type ExceptionBuilder() =
member this.Bind (m, f) =
match m with
| Success a -> f a
| Failure m -> Failure m
member this.Return (x) =
Success (x)
let ex = new ExceptionBuilder()
let divide n m =
if m = 0 then Failure "Cannot divide by zero"
else Success ((float n)/(float m))
let round (f : float) =
Success (System.Math.Round(f, 3))
let divideRoundAndPrintNumber a b =
ex {
let! c = divide a b
let! d = round c
printf "result of divideRoundAndPrintNumber: %f\n" d
return d
}
let result = divideRoundAndPrintNumber 11 0
match result with
| Success r -> printf "%f\n" r
| Failure m -> printf "%s\n" m
Apologies when my answer does not match your question completely but I hope it helps.
Here you can find an excellent blog post series about this topic:
http://fsharpforfunandprofit.com/posts/computation-expressions-intro/
I also found this article very enlightening:
http://adit.io/posts/2013-04-17-functors,_applicatives,_and_monads_in_pictures.html
Monads have a fairly strict required structure, they must have:
Return: 'a -> m<'a>
and
Bind: m<'a> -> ('a -> m<'b>) -> m<'b>
Your divide function has the signature int*int -> MException<float>, i.e. it does indeed have the required 'a -> m<'b> form to be used with bind. When used with bind, it would act on something of type MException<int*int> and produce an MException<float>.
If divide is instead of type int -> int -> MException<float> (i.e. 'a -> 'b -> m<'c>'), we can't use it with bind directly. What we can do is unwrap the tuple and then supply the arguments one by one to create a lambda that does have the right form.
Let's add an extra Return so that we can see more clearly some different approaches for handling functions within these constraints:
let divideTupled (n, m) =
match m with
| 0 -> Failure "Cannot divide by zero"
| _ -> Success ((float n) / (float m))
let divideRoundAndPrintNumber n m =
MException<_>.Return (n,m)
|> MException<_>.Bind divideTupled
|> MException<_>.Bind round
|> MException<_>.Map toString
or
let divideCurried n m =
match m with
| 0 -> Failure "Cannot divide by zero"
| _ -> Success ((float n) / (float m))
let divideRoundAndPrintNumber n m =
MException<_>.Return (n,m)
|> MException<_>.Bind (fun (n,m) -> divideCurried n m)
|> MException<_>.Bind round
|> MException<_>.Map toString
Computation expressions, as mentioned by Olaf, provide some nice syntactic sugar for working with monads in F#.
Why not define divide like you normally would?
let divide n m =
match m with
| 0 -> Failure "Cannot divide by zero"
| _ -> Success ((float n) / (float m))
You could then define divideRoundAndPrintNumber like this, likewise in curried form:
let divideRoundAndPrintNumber n m =
divide n m
|> MException<_>.bind round
|> MException<_>.map toString
FSI ad-hoc tests:
> let result = divideRoundAndPrintNumber 11 3;;
val result : MException<string> = Success "3.667000"
> let result = divideRoundAndPrintNumber 11 0;;
val result : MException<string> = Failure "Cannot divide by zero"

What is wrong in F# code?

In F# I am trying to get last element of give list. I wrote below code
let rec findLast t =
match t with
| hd :: [] -> hd
| hd :: tl -> findLast tl
| _ -> -1
printfn "%A" (findLast [1,2,3,4,5])
But when I tried to execute it in F# Interactive it complain as below
error FS0001: This expression was expected to have type
int but here has type
'a * 'b * 'c * 'd * 'e
I just want to know what is wrong in above code. I know there are different smart and elegant ways to get last element from list in F#. But I am interested to know what is wrong in above code ?
1,2,3,4,5 is a tuple. 'a * 'b * 'c * 'd * 'e is a tuple definition. Create a list with semicolons [1;2;3;4;5]. [1,2,3,4,5] is a list of tuples with one item which is a quintuple.
let rec findLast t =
match t with
| hd :: [] -> hd
| hd :: tl -> findLast tl
| _ -> -1
printfn "%A" (findLast [1;2;3;4;5])
Try this one:
let rec lastElem = function
| [] -> None
| [x] -> Some x
| x::xs -> lastElem xs
You can try it in the REPL:
> lastElem [1;2;3];;
val it : int option = Some 3
> lastElem ["a";"b";"c"];;
val it : string option = Some "c"
As #Phillip-Scott-Givens pointed out, you've likely made a totally common (especially for C#'ers), error and used a comma to separate a list instead of a semi-colon.
This results in a tuple list [(1, 2, 3, 4, 5)] and not an integer list [1;2;3;4;5]. Getting unexpected asterisks in your type definitions is a symptom of this :)
That said, here a few different functions that get the last value from your tuple, list, and tuple list (ref: https://stackoverflow.com/a/1175123/5470873):
// Data:
let tuples = [ (1,2,3,4,5); ] // = [1,2,3,4,5]
let firstListElement = tuples.[0]
// Access:
let rec lastItemInList = function
| hd :: [] -> hd
| hd :: tl -> lastItemInList tl
| _ -> failwith "Empty list."
let lastValueOfFirstItem = function
| (_, _, _, _, last) :: _ -> last
| _ -> -1
let lastValueOfTuple = function _, _, _, _, last -> last
// same as: let lastValueOfTuple myTuple =
// match myTuple with
// | (_, _, _, _, last) -> last
// Examples:
tuples |> lastItemInList // val it : int * int * int * int * int = (1, 2, 3, 4, 5)
tuples |> lastValueOfFirstItem // val it : int = 5
tuples |> List.map lastValueOfTuple // val it : int list = [5]
firstListElement |> lastValueOfTuple // val it : int = 5

Strange (?) type mismatch error in this function

Can someone explain why compiler is giving me this error
Type mismatch. Expecting a
'a [] -> string
but given a
'a [] -> 'a []
The type 'string' does not match the type ''a []'
on this code snippet:
let rotate s: string =
[|for c in s -> c|]
|> Array.permute (function | 0 -> (s.Length-1) | i -> i-1)
while the one below compiles just fine:
let s = "string"
[|for c in s -> c|]
|> Array.permute (function | 0 -> (s.Length-1) | i -> i-1)
Your first snippet defines function rotate with return type of string.
Try to change it to:
let rotate (s: string) =
[|for c in s -> c|]
|> Array.permute (function | 0 -> (s.Length-1) | i -> i-1)
In this form you define a function with one string argument (I suppose that's what you wanted) and inferred return type.

Resources