I am new to F# and wanna do as the title says, but I keep getting these type errors.
I know this works:
> let rec validString2 =
function
| a -> Map.find a
> validString2 "x" (Map.ofList [("x", 5)]);;
>val it: int = 5
But I wanna return Map.find a
only if a
is in the map, otherwist I wanna return 0. When I try this:
let rec validString =
function
| a -> if (Map.containsKey a) then Map.find a else 0
The errors message I get (and red underline under Map.containsKey a
):
This expression was expected to have type
'bool'
but here has type
'Map<'a,'b> -> bool'
The same happens if I tried:
let validString =
function
| Some x -> x
| None -> 0
let rec evalValidString =
function
| V a -> validString (Map.tryFind a)
It seems I'm misunderstanding how types with maps work. I don't understand how bool is different from Map<'a, 'b> -> bool. The map function returns a bool, I should be able to evaluate it.
CodePudding user response:
I think the problem here is that you have to specify the map you want to search. In the function below, I've named it myMap
:
let myLookup (key : string) myMap =
myMap
|> Map.tryFind key // does the key exist in myMap?
|> Option.defaultValue 0 // if not, return 0
Note that myMap
is a value of type Map<string, int>
. You could then use this function as follows:
let aMap = Map.ofList [("x", 5)]
let xValue = myLookup "x" aMap
let yValue = myLookup "y" aMap
printfn "%A" (xValue, yValue) // 5, 0