Consider the following PureScript code, which is trying to convert a Number into an Integer.
module Main where
import Prelude (discard, Unit)
import Prelude (($))
import Data.Int ( toStringAs, fromNumber, decimal )
import Data.Maybe ( fromMaybe )
myNumber :: Number
myNumber = 4.762
myInteger :: Int
myInteger = fromMaybe (0 $ (fromNumber myNumber))
However this code produces the following error,
Could not match type
Int
with type
t0 -> t1
Not sure how to use fromMaybe correctly here as this use case doens't seem to be documented yet.
So the question is, What is the correct syntax for converting a number to an integer?
It's not 100% clear what you're trying to do, but it kinda looks like you have an extra set of parens.
myInteger = fromMaybe (0 $ (fromNumber myNumber))
^ ^
| |
these two are detrimental
The expression inside these two parens is:
0 $ (...)
If you look at the definition or the docs for the $
operator, you'll see that its left argument is supposed to be a function.
right argument
|
v
0 $ (...)
^
|
left argument
But PureScript sees a 0
(of type Int
) instead of a function.
And so it rightly complains: cannot match type Int
with type (function type)
What I'm guessing you actually meant is to (1) try to convert the Number
to an Int
with fromNumber
, and (2) if that fails, substitute zero with fromMaybe
.
If you look at the definition of fromMaybe
, you'll see that it has two arguments: first argument is the default value and second argument is the Maybe
value. So all you need to do is just call fromMaybe
with those two arguments:
second argument
|
------------------
/ \
v v
myInteger = fromMaybe 0 (fromNumber myNumber)
^
|
first argument
I really don't understand how you could possibly get the idea of writing 0 $ (...)
, so I cannot address that particular misunderstanding, sorry.