哈斯克尔.将名称分配给值的阈值

Uns*_*der -1 haskell function threshold

我想弄清楚如何在Haskell中编写:

有一个由4个变量组成的列表:[w,x,y,z]通过ghci完成以下内容后:

collection :: Int -> Int -> Int -> Int -> [Int]
collection w x y z = [w,x,y,z]
Run Code Online (Sandbox Code Playgroud)

我想为w,x,y,z的每个阈值赋予"含义".例如:当0 <x <60时,则x ="低",当59 <x <80时,则x ="中",当79 <x <100时,则x ="高"

你如何把它放在Haskell代码中?

Alb*_*oso 5

如果我正确理解了你想要的东西,你可以定义一个函数,将你所谓的"含义"分配给一个整数,然后将集合列表映射到它上面:

bin :: Int -> String
bin x
  | x <= 0    = error "nonpositive value"
  | x < 60    = "Low"
  | x < 80    = "Medium"
  | x < 100   = "High"
  | otherwise = error "value greater than or equal to 100"

binnedCollection :: Int -> Int -> Int -> Int -> [String]
binnedCollection w x y z = map bin $ collection w x y z
Run Code Online (Sandbox Code Playgroud)

例如,

Prelude> binnedCollection 0 20 60 80
["Low","Low","Medium","High"]
Run Code Online (Sandbox Code Playgroud)

我添加了定义中未包含的范围的错误情况; 将它们更改为适合您逻辑的任何内容.

  • 更好的是,使用自定义数据类型,*只有*三个可能的值而不是`String`作为返回值.`数据阈值=低| 中| 高`,然后`bin x | x <60 =低等等 (2认同)