-1

Consider the following simple code example,

module Main where

import Prelude (discard, Unit, ($))
import Effect (Effect)
import Effect.Console (log)
import Data.Int ( toStringAs, fromNumber, decimal )
import Data.Maybe ( fromMaybe )

myNumber :: Number
myNumber = 4.762

myInteger :: Int
myInteger = fromMaybe 0 (fromNumber myNumber)

main ∷ Effect Unit
main = do
  log ( toStringAs decimal myInteger )

The expected value would be

4

However, the output of this code is

0

Question: Why does fromMaybe return 0 instead of the maybe value (4) ?

duplode
  • 33,731
  • 7
  • 79
  • 150
Code Whisperer
  • 22,959
  • 20
  • 67
  • 85
  • I’m voting to close this question because there's a typo in the name and i can't change the name *shrug* – Code Whisperer Apr 06 '22 at 17:13
  • A typo in the name? I assume you mean the double negative I just fixed; I don't know what problem you had with that. – dfeuer Apr 06 '22 at 20:12

1 Answers1

2

Your problem is not with fromMaybe, but with fromNumber (btw, pro tip: when you see a problem, never assume you know what the cause is; if you have a hypothesis for the cause, check it first, only then try to fix).

Once again, read the docs. Quote:

The number must already be an integer and fall within the valid range of values for the Int type otherwise Nothing is returned.

Your number is not an integer, so fromNumber returns Nothing, just like it promised.


Judging by your expected output, what you probably actually want is floor.

Fyodor Soikin
  • 78,590
  • 9
  • 125
  • 172
  • I think it's a fair mistake to make to think that the value passed to fromNumber ought to be a number – Code Whisperer Apr 06 '22 at 17:06
  • Assuming your goal in answering questions is to create fertile grounds for learning for future leaners, I do not think this answer will be of as much use to future PureScript learners as your previous answers @FyodorSoikin - could you kindly provide an example of code that would successfully convert an Integer to a number / number to an integer? – Code Whisperer Apr 06 '22 at 17:08
  • Is this a good place to point out the docs would be much more useful if they contained examples... – Code Whisperer Apr 06 '22 at 17:10
  • I have rolled this discussion into an ew question @Fyodor and closed this one. Thank you! https://stackoverflow.com/questions/71771009/purescript-convert-a-number-to-an-integer – Code Whisperer Apr 06 '22 at 17:13