簡體   English   中英

PureScript無法將類型Maybe Int與類型Int匹配

[英]PureScript Could not match type Maybe Int with type Int

我正在做“ PureScript示例”一書中的分配,以使用遞歸來計算數組中偶數個項目的數量。

這是我寫的代碼

isEven :: Int -> Boolean
isEven 0 = true
isEven 1 = false
isEven n = isEven(n - 2) 

countEven :: List Int -> Int
countEven list = 
   if null list 
   then 0
   else 
      if isEven(unsafePartial (head list)) 
      then 1 
      else 0 + countEven(unsafePartial (tail list))

我收到一條錯誤消息,說

Error found:
in module Main
at src/Main.purs line 74, column 17 - line 74, column 42

  Could not match type

    Maybe Int

  with type

    Int


while checking that type t0
  is at least as general as type Int
while checking that expression unsafePartial (head list)
  has type Int
in binding group countEven

我對此感到有些驚訝,因為unsafePartial head list的數據類型為Int, unsafePartial tail list的數據類型為List Int

那么,為什么感覺某個地方可能有Maybe?

出現此錯誤的事實意味着您正在使用Data.List headtail ,它們實際上並不是局部的,而是返回Maybe

要使用它們的部分對應項,請從Data.List.Partial導入它們。

您應該使用uncons而不是使用這樣的重錘的unsafePartial ,因為它可以很容易滑出你的手...

如果您真的想手動編寫此遞歸(我認為這是一種反模式),則可以如下編寫:

module Main where

import Data.Array (uncons)
import Data.Maybe (Maybe(..))

isEven :: Int -> Boolean
isEven n = n `mod` 2 == 0

countEven l =
  case uncons l of
    Just { head, tail } ->
      let
        s =
         if isEven head
         then 1
         else 0
      in
        s + countEven tail
    Nothing -> 0

這是try.purescript.org上此片段的交互式版本。

如前所述,您應避免使用unsafePartialPartial因為它們會破壞對程序整體的信心。 整體性是任何程序的真正有價值的功能。 總的來說,我認為使用更高級別的工具(例如foldfoldMap + ala比“原始遞歸程序集”要好得多。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM