本文介绍了构造具有许多字段的Haskell数据类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有数据类型

  data常量=常量{x1 :: Int,x2 :: Int, x100 :: Int} 

名称x1,x2,...,x100可能有不正确的命名。 / p>

是否有一种优雅的方法来从100个Int值列表中创建Constants对象?

  mkConstants :: [Int]  - >常量
mkConstants [x1,x2,...,x100] =常量x1 x2 ... x100 - 错误的方式

反向任务呢?

  extractInts :: Constants  - > [Int] 
extractInts(常量x1 x2 ... x100)= [x1,x2,...,x100] - 糟糕的方式


解决方案

编辑:请参阅,当记录字段类型不同(即不是全部int)时,修改版本。






一种可能性是使用类型类:

  { - #LANGUAGE FlexibleInstances# - } 

数据常量=常量{a :: Int,b :: Int,c :: Int,d :: Int,e :: Int}
派生显示

class缺省位置
cons :: a - > [Int] - >可能常数

实例缺省常数其中
cons c [] = Just c
cons _ _ = Nothing

实例(Cons a)=>缺点(Int - > a)其中
cons f(x:xs)= cons(fx)xs
cons _ _ = Nothing

那么,如果列表是正确的大小:

  \\> cons常数[1..5] 
Just(常数{a = 1,b = 2,c = 3,d = 4,e = 5})
pre>

否则不会有任何结果:

  \> cons常量[1..4] 

\> cons常数[1..6]


I have data type

data Constants = Constants { x1 :: Int, x2 :: Int, ... , x100 :: Int }

Names x1, x2, ..., x100 may have irregular naming.

Is there an elegant way to create Constants object from list of 100 Int values?

mkConstants :: [Int] -> Constants
mkConstants [x1, x2, ..., x100] = Constants x1 x2 ... x100 -- The bad way

What about reverse task?

extractInts :: Constants -> [Int]
extractInts (Constants x1 x2 ... x100) = [x1, x2, ..., x100] -- The bad way
解决方案

Edit: see Reading long data structure in Haskell for a modified version when the record fields are of different types (i.e. not all ints).


One possibility would be to use type classes:

{-# LANGUAGE FlexibleInstances #-}

data Constants = Constants { a :: Int, b :: Int, c :: Int, d :: Int, e :: Int }
    deriving Show

class Cons a where
    cons :: a -> [Int] -> Maybe Constants

instance Cons Constants where
    cons c [] = Just c
    cons _ _  = Nothing

instance (Cons a) => Cons (Int -> a) where
    cons f (x:xs) = cons (f x) xs
    cons _ _      = Nothing

then, if the list is of the right size:

\> cons Constants [1..5]
Just (Constants {a = 1, b = 2, c = 3, d = 4, e = 5})

and otherwise you get nothing:

\> cons Constants [1..4]
Nothing
\> cons Constants [1..6]
Nothing

这篇关于构造具有许多字段的Haskell数据类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-04 12:20
查看更多